Much of this page is from the SUN tutorial. Overview of Applets


Java Applets and Appletviewer: The Life Cycle of an Applet

The most common Java programs are applications and applets. Applications are standalone programs, such as the HotJava browser. Applets are similar to applications, but they don't run standalone. Instead, applets adhere to a set of conventions that lets them run within a Java-compatible browser. As such, applets do not use the main() method; they assume that the user is executing the Java code from within a browser.

To run Java applets, you can use the JDK Applet Viewer or any Java-compatible Web browser, such as the HotJava browser. (Note that both of these browsers are also Java applications.) In this section, we will be discussing both applets and the generalities of browsers as they relate to the use of applets (so basically focusing on appletviewer)

The primary function of this application is to provide the user with an object of type Graphics to draw upon, and several functions to facilitate the use of the Graphics object.

Loading the Applet

When an applet is loaded into a browser, it begins its life cycle:

Leaving and Returning to the Applet's Page

When the user leaves the page -- for example, to go to another page -- the applet has the option of stopping itself. When the user returns to the page, the applet can start itself again. The same sequence occurs when the user iconifies and then reopens the window that contains the applet. (Other terms used instead of iconify are minaturize, minimize, and close.)

Thus, there are four methods in the Applet class that give you the framework on which you build any serious applet.

Methods for Milestones

public class Simple extends Applet {
    . . .
    public void init() { . . . }
    public void start() { . . . }
    public void stop() { . . . }
    public void destroy() { . . . }
    . . .
}
The Simple applet, like every other applet, features a subclass of the Applet class. The Simple class overrides four Applet methods so that it can respond to major events:

init
To initialize the applet each time it's loaded (or reloaded). Common actions in an applet include processing PARAM values and adding user-interface components
start
To start the applet's execution, such as when the applet's loaded or when the user revisits a page that contains the applet. This means that the start can be called repeatedly, unlike the init
stop
To stop the applet's execution, such as when the user leaves the applet's page or quits the browser. (iconify)
destroy
To perform a final cleanup in preparation for unloading.

Note: init for new instance (reload) vs. start for same instance (restart).
Not every applet needs to override every one of these methods. Some very simple applets override none of them. For example, the "Hello World" applet doesn't override any of these methods, since it doesn't do anything except draw itself. The "Hello World" applet just displays a string once, using its paint method. Most applets, however, do more.

The init method is useful for one-time initialization that doesn't take very long. In general, the init method should contain the code that you would normally put into a constructor. The reason applets shouldn't usually have constructors is that an applet isn't guaranteed to have a full environment until its init method is called. For example, the Applet image loading methods simply don't work inside of a applet constructor. The init method, on the other hand, is a great place to call the image loading methods, since the methods return quickly.

Every applet that does something after initialization (except in direct response to user actions) must override the start method. The start method either performs the applet's work or (more likely) starts up one or more threads to perform the work.

Most applets that override start should also override the stop method. The stop method should suspend the applet's execution, so that it doesn't take up system resources when the user isn't viewing the applet's page. For example, an applet that displays animation should stop trying to draw the animation when the user isn't looking at it.

Many applets don't need to override the destroy method, since their stop method (which is called before destroy) does everything necessary to shut down the applet's execution. However, destroy is available for applets that need to release additional resources.

Methods for Drawing

The appletviewer also includes the Component class, which uses the following methods to help the applet write onto the graphics space provided by the appletviewer.

It is useful to be aware that every applet is implemented by creating a subclass of the Applet class. The following figure shows the inheritance hierarchy of the Applet class. This hierarchy determines much of what an applet can do and how.

java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.Panel
                           |
                           +----java.applet.Applet

The Simple applet defines its onscreen appearance by overriding the paint method:

class Simple extends Applet {
    . . .
    public void paint(Graphics g) { . . . }
    . . .
}

The paint method is one of two display methods an applet can override:

paint
The basic display method. Many applets implement the paint method to draw the applet's representation within a browser page.
update
A method you can use along with paint to improve drawing performance.

Applets inherit their paint and update methods from the Applet class, which inherits them from the Abstract Window Toolkit (AWT) Component class.

How Drawing Requests Occur

Programs can draw only when the AWT tells them to. The reason is that each occurrence of a Component drawing itself must execute without interruption. Otherwise, unpredictable results could occur, such as a button being drawn halfway, and then being interrupted by some lengthy animation. The AWT orders drawing requests by making them run in a single thread. A Component can use the repaint() method to request to be scheduled for drawing.

The AWT requests that a Component draw itself by invoking the Component's update() method. The default (Component) implementation of the update() method simply clears the Component's background (drawing a rectangle over the component's clipping area in the Component's background color) and then calling the Component's paint() method. The default implementation of the paint() method does nothing.

The Graphics Object

The only argument to the paint() and update() methods is a Graphics object that represents the context in which the Component can perform its drawing. The Graphics class provides methods for the following:

How to Draw

The simplest way for a Component to draw itself is to put drawing code in its paint() method. This means that when the AWT makes a drawing request (by calling the Component's update() method) the Component's entire area is cleared and then its paint() method is called. For programs that don't repaint themselves often, the performance of this scheme is fine.

Important: The paint() and update() methods must execute very quickly! Otherwise, they'll destroy the perceived performance of your program. If you need to perform some lengthy operation as the result of a paint request, do it by starting up another thread (or somehow sending a request to another thread) to perform the operation.

Programs that repaint themselves often can use two techniques to improve their performance: implementing both update() and paint(), and using double buffering.
These techniques are discussed in
Working with Graphics and later in our notes on Double-Buffering (in particular help from SUN )


Summary

In your Applet subclass, you must implement at least one of the following methods: init, start, and paint. The init and start methods, along with stop and destroy, are called when major events (milestones) occur in the applet's life cycle. The paint method is called when the applet needs to draw itself to the screen.

The Applet class extends the AWT Panel class, which extends the AWT Container class, which extends the AWT Component class. From Component, an applet inherits the ability to draw and handle events. From Container, an applet inherits the ability to include other components and to have a layout manager control the size and position of those components. From Applet, an applet inherits several capabilities, including the ability to respond to major milestones, such as loading and unloading.

You include applets in HTML pages using the <APPLET> tag. When a browser user visits a page that contains an applet, here's what happens:

  1. The browser finds the class file for the applet's Applet subclass. The location of the class file (which contains Java bytecodes) is specified with the CODE and CODEBASE attributes of the <APPLET> tag.
  2. The browser brings the bytecodes over the network to the user's computer.
  3. The browser creates an instance of the Applet subclass. When we refer to an applet, we're generally referring to this instance.
  4. The browser calls the applet's init method. This method performs any one-time initialization that is required.
  5. The browser calls the applet's start method. This method often starts a thread to perform the applet's duties.

An applet's Applet subclass is its main, controlling class, but applets can use other classes, as well. These other classes can be either local to the browser, provided as part of the Java environment, or custom classes that you supply. When the applet tries to use a class for the first time, the browser tries to find the class on the host that's running the browser. If the browser can't find the class there, it looks for the class in the same place that the applet's Applet subclass came from. When the browser finds the class, it loads its bytecodes (over the network, if necessary) and continues executing the applet.

Loading executable code over the network is a classic security risk. For Java applets, some of this risk is reduced because the Java language is designed to be safe -- for example, it doesn't allow pointers to random memory. In addition, Java-compatible browsers improve security by imposing restrictions. These restrictions include disallowing applets from loading code written in any non-Java language, and disallowing applets from reading or writing files on the browser's host.

See What Applets Can and Can't Do for more on these restrictions.