The Applet class is an AWT class and is not designed to work with Swing components. To use Swing components in Java applets, it is necessary to create a Java applet that extends javax.swing.JApplet , which is a subclass of java.applet.Applet . JApplet inherits all the methods from the Applet class. In addition, it provides support for laying out Swing components.
To add a component to an applet, you add it to the content pane of an applet, which is similar to adding a component to the content pane of a frame. By default, the content pane of JApplet uses BorderLayout . Here is an example of a simple applet that uses JLabel to display a message.
// WelcomeApplet.java: Applet for displaying a message import javax.swing.*; public class WelcomeApplet extends JApplet { /** Initialize the applet */ public void init() { add ( new JLabel( "Welcome to Java" , JLabel.CENTER)); } }
Note
The content pane delegation feature in JDK 1.5 allows you to invoke the add method from an applet to place components to the content pane of an applet. Strictly speaking, a component is added into the content pane of an applet. But for simplicity we say that a component is added to an applet. |
You cannot run this applet standalone, because it does not have a main method. To run this applet, you have to create an HTML file with the applet tag that references the applet. When you write Java GUI applications, you must create a frame to hold graphical components, set the frame size , and make the frame visible. Applets are run from the Web browser. The Web browser automatically places the applet inside it and makes it visible. The following section shows how to create HTML files for applets.
Note
You may rewrite the WelcomeApplet by moving the code in the init method to the no-arg constructor, as follows : // WelcomeApplet.java: Applet for displaying a message import javax.swing.*; public class WelcomeApplet extends JApplet { /** Construct the applet */ public WelcomeApplet() { add ( new JLabel( "Welcome to Java" , JLabel.CENTER)); } } |