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:

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

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 ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.