The Life Cycle of an Applet

Started by sukishan, Jul 15, 2009, 03:07 PM

Previous topic - Next topic

sukishan

The Life Cycle of an Applet
Here is the Simple applet.
The following is the source code for the Simple. The Simple applet displays a descriptive string whenever it encounters a major milestone in its life, such as when the user first visits the page the applet's on. The pages that follow use the Simple applet and build upon it to illustrate concepts that are common to many applets. If you find yourself baffled by the Java source code, you might want to go to Learning the Java Language to learn about the language.

import java.applet.Applet;
import java.awt.Graphics;

//No need to extend JApplet, since we don't add any components;
//we just paint.
public class Simple extends Applet {

    StringBuffer buffer;

    public void init() {
        buffer = new StringBuffer();
        addItem("initializing... ");
    }

    public void start() {
        addItem("starting... ");
    }

    public void stop() {
        addItem("stopping... ");
    }

    public void destroy() {
        addItem("preparing for unloading...");
    }

    private void addItem(String newWord) {
        System.out.println(newWord);
        buffer.append(newWord);
        repaint();
    }

    public void paint(Graphics g) {
   //Draw a Rectangle around the applet's display area.
        g.drawRect(0, 0,
         getWidth() - 1,
         getHeight() - 1);

   //Draw the current string inside the rectangle.
        g.drawString(buffer.toString(), 5, 15);
    }
}

Loading the Applet
You should see "initializing... starting..." above, as the result of the applet being loaded. When an applet is loaded, here's what happens:
* An instance of the applet's controlling class (an Applet subclass)is created.
* The applet initializes itself.
* The applet starts running.

Leaving and Returning to the Applet's Page
When the user leaves the page — for example, to go to another page — the browser stops the applet. When the user returns to the page, the browser starts the applet.

Reloading the Applet

Some browsers let the user reload applets, which consists of unloading the applet and then loading it again. Before an applet is unloaded, it's given the chance to stop itself and then to perform a final cleanup, so that the applet can release any resources it holds. After that, the applet is unloaded and then loaded again, as described in Loading the Applet, above.

Quitting the Browser
When the user quits the browser (or whatever application is displaying the applet), the applet has the chance to stop itself and do final cleanup before the browser exits.
A good beginning makes a good ending

lucasjen

The life cycle of an applet is determined by methods that are automatically called at its birth. The applet has the option of stopping itself. The basic life cycle of an applet is init(),  start(),  stop().