O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The JApplet Class

JApplet is a simple extension of java.applet.Applet to use when creating Swing programs designed to be used in a web browser (or appletviewer ). As a direct subclass of Applet, JApplet is used in much the same way, with the init( ) , start( ), and stop( ) methods still playing critical roles. The primary thing JApplet provides that Applet does not is the use of a JRootPane as its single display component. The properties and methods described below should look a lot like those described in the previous sections on JFrame and JWindow. Figure 8-11 shows a JApplet running in appletviewer.

A JApplet running in the SDK appletviewer

Figure 8-11. A JApplet running in the SDK appletviewer

Here’s the code for this simple applet:

// SimpleApplet.java
//
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;

public class SimpleApplet extends JApplet {
  public void init( ) {
    JPanel p = new JPanel( );
    p.setLayout(new GridLayout(2, 2, 2, 2));
    p.add(new JLabel("Username"));
    p.add(new JTextField( ));
    p.add(new JLabel("Password"));
    p.add(new JPasswordField( ));
    Container content = getContentPane( );
    content.setLayout(new GridBagLayout( )); // Used to center the panel
    content.add(p);
  }
}

Using JApplet in browsers is a bit trickier. You should have a browser that supports at least the 1.2 release of the JRE. You typically end up using the Java Plug-in. The Plug-in allows you to specify which version of the JRE ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required