Java: Applets

Why no applets in these notes

These notes were originally written using applets almost entirely. However, all applet examples are being changed to applications.

Converting Applets to Applications

To make an applet into an application, add a main()method to the applet's class -- you don't have to create a new class. It may seem a little strange that adding a main method to a class will make it into an application, but that's the most common way of doing it. An application is any program that has a main() method. This new main() does what a browser does.

The main method should do the following:

  1. Create a window (JFrame) to hold the applet.
  2. Make the window's close box stop the applet.
  3. Create a new applet object, and add it to the window.
  4. Start the applet by calling init(), then start().
  5. Finalize the layout.
  6. Make the window (with the applet in it) visible.

Example

Here is a very small applet, which just displays some text.

import javax.swing.*;

public class SampleApplet extends JApplet {
    public SampleApplet() {
        add(new JLabel("This is an Applet."));
    }
}

Add a main() method, and it can be used as either an application or an applet.

import java.awt.*;
import javax.swing.*;

public class SampleApplet extends JApplet {
    
    public static void main(String[] args) {
        JFrame myWindow = new JFrame("SampleApplet Application");
        myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SampleApplet theApplet = new SampleApplet(); // Create a new object.
        myWindow.setContentPane(theApplet);  // Add to the window.
        //theApplet.init();           // Needed if defined in applet
        //theApplet.start();          // Needed if defined in applet
        myWindow.pack();              // Arrange the components.
        myWindow.setVisible(true);    // Make the window visible.
    }
    
    // Constructor
    public SampleApplet() {
        add(new JLabel("This is an Applet and and Application!"));
    }
}

Some applets may use features that require additional work.

The <applet...> HTML tag

You need to specify the following values in an applet tag.

Example tag

<applet code="mousedemo.MouseTest.class" archive="mousedemo.jar" width="400" height="200"></applet>