Every applet must define a subclass of the
Applet
orJApplet
class. In the Hello World applet, this subclass is calledHelloWorld
. The following is the source for theclass.
HelloWorld
import javax.swing.JApplet; import javax.swing.SwingUtilities; import javax.swing.JLabel; public class HelloWorld extends JApplet { //Called when this applet is loaded into the browser. public void init() { //Execute a job on the event-dispatching thread; creating this applet's GUI. try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { JLabel lbl = new JLabel("Hello World"); add(lbl); } }); } catch (Exception e) { System.err.println("createGUI didn't complete successfully"); } } }Applets inherit significant functionality from the
Applet
orJApplet
class, including the capabilities to communicate with the browser and present a graphical user interface (GUI) to the user.An applet that will be using GUI components from Swing (Java's GUI toolkit) should extend the
javax.swing.JApplet
base class, which provides the best integration with Swing's GUI facilities.
JApplet
provides a root pane, which is the same top-level component structure as Swing'sJFrame
andJDialog
components, whereasApplet
provides just a basic panel. See How to Use Root Panes for more details on how to utilize this feature.An applet can extend the
java.applet.Applet
class when it does not use Swing's GUI components.