Swing introduction  Swing components  Events and listeners  Text fields/labels  Layouts  JPanel and Box


Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java
 Comment on this article  List of Java topics

Java Applets: the JApplet class

Having introduced the concept of Java applets, it's time to see how the code to a skeleton applet looks. Essentially, an applet overrides the JApplet class1, providing an implementation of at least the init() method:

public class MyAppletClass extends JApplet {
  public void init() {
    try {
      SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
          addComponents();
        }
      });

      // non-GUI initialisation
    } catch (Exception ex) {
      throw new RuntimeException("Error initting");
    }
  }

  public void destroy() {
    // perform any cleanup
  }
}

The init() method is intended to be called when the applet has been loaded by the browser (or other applet container— we'll assume a web browser for the sake of argument). This is where any components can be added to the applet. Note the call to SwingUtilities.invokeAndWait(). You may not have used this method before, but maybe you've used the related call to invokeLater() which, as you'll recall, makes the given run() method be executed in the event thread. In other words, it's the construct we need to use when we modify the user interface from some thread that isn't the Swing event thread (or, put another way, when we're not being called from a Swing event handler such as actionPerformed() etc).

Well, the init() method is indeed called by some arbitrary thread, and we want to modify the user interface. But we may also want to do some other non-UI related initialisation. So in this case, the SwingUtilities.invokeAndWait() variant asks the event thread to execute the given run() method, as with its cousin invokeLater(), but then it waits for that run() method to be completed, before allowing the rest of our init() method to complete.

The destroy() method, which actually many applets will not need to implement, allows you to perform any cleanup code. If your cleanup is simply removing GUI components and disposing of normal objects, for example, the applet container will handle this automatically and you don't need to override destroy().

Adding components to the applet

Your applet is itself a Swing component. You can treat it as a plain old JPanel (with a default BorderLayout), add components to it, query its size, and override its paintComponent() method and draw directly on to its surface. Note that, as of Java 5, you can add components directly to the JApplet— you don't need to call getRootPane() as mentioned in earlier Swing/applet tutorials.

The start() and stop() methods

In addition to the init() and desotry() methods, two other important methods are called within the life cycle of an applet and which it may be useful to override: start() and stop(). The difference between these and the init()/destroy() methods is subtle, but essentially, an applet that wants to perform an animation or some other task "automatically" (i.e. without waiting for user input) on becoming visible should start and stop this activity inside start() and stop(). In principle, it is possible for an applet to be stopped and started multiple times durings its lifetime (although this doesn't appear to happen with many modern browsers— in practice, the applet is initted and started when the page is displayed, and stopped and destroyed when the page is closed).


1. Iif it doesn't use the Swing library, it can in theory override the "raw" Applet class. Doing so is probably rare nowadays.


Unless otherwise stated, the Java programming articles and tutorials on this site are written by Neil Coffey. Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Javamex UK 2009. All rights reserved.