Class java.applet.Applet

Applet is a program that runs embedded in a larger program, typically a web browser.

The program that contains the applet determines when the applet starts and finishes. It can also pause and unpause the applet, for example when the web browser is minimized or the user switches to another tab.

These events are announced to the applet by calling its lifecycle methods: "init", "start", "stop" and "destroy". Of these methods, "init" is always called the first, and it is only called once for the given instance of applet. Analogically, "destroy" is always called the last, and it is only called once. Methods "start" and "stop" can be called multiple times, as the user switches among the browser tabs. So, for example, a simple lifecycle would be calling "init" and "start", and then later "stop" and "destroy".

The default implementations of these methods are empty; it is not necessary to call them. Methods "start" and "stop" can be used to start and stop animation threads. Methods "init" and "destroy" are used to initialize and destroy the applet instance. It is better to avoid calling other applet methods from constructor, because at that moment the applet is not fully initialized yet. There is no guarantee that these methods are called within the AWT/Swing event thread, so it is probably safer to wrap the code in "SwingUtilities.invokeLater" method calls.

An example applet with green background and "MyApplet" label, which displays debugging messages in the Java console on each event:

public class MyApplet extends Applet {

  @Override
  public void init() {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        System.out.println("Initalizing Applet");
        setBackground(Color.GREEN);
        add(new JLabel("My Applet"));
      }
    });
  }

  @Override
  public void start() {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        System.out.println("Starting Applet");
      }
    });
  }

  @Override
  public void stop() {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        System.out.println("Stopping Applet");
      }
    });
  }

  @Override
  public void destroy() {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        System.out.println("Destroying Applet");
      }
    });
  }

}

viliam@bur.sk