All of my tutorials thus far have been using JFrame to create windows. However, Java also supports the Applet, this enables your applications to be viewable in your internet browser. All swing components that have been discussed in my previous tutorials can be used in an Applet. Lets take a look at how an applet with a JButton might look.
We are going to start with our basic class:
Java Code:
package tutorials;
public class ApplTut {
public ApplTut() {
}
}
When creating the basic class, one of the main differences between a java application and an java applet is that applets do not use the
Java Code:
public static void main
(String args[]
)
as its main method for instantiation - it uses the init method.
First we must extend the JApplet, just as we extend JFrame when making applications. Also we import javax.swing.JApplet.
Java Code:
package tutorials;
import javax.swing.JApplet;
public class ApplTut
extends JApplet {
public ApplTut() {
}
}
Next we add the init method.
Java Code:
package tutorials;
import javax.swing.JApplet;
public class ApplTut
extends JApplet {
public ApplTut() {
}
public void init() {
}
}
And that is the basic shell of an applet. To add swing components, use the same method's you would for an application. Here is an example of how you would add a JButton.
Java Code:
package tutorials;
import javax.swing.JApplet;
import javax.swing.JButton;
public class ApplTut
extends JApplet {
public ApplTut() {
}
public void init() {
add(button);
}
}