What is an Applet, and its Life Cycle

An Applet, is used to develop Graphical User Interface Programs in Java.

Also Applets can be embedded as part of a HTML form. All Apllets need to inherit from java.applet.Applet class. Below are Life Cycle Methods, which need to be ovveridden in the Derived class of Applet

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

/*
<applet code="AppletLifeCycleExample" width=150 height=150>
</applet>
*/

public class AppletLifeCycleExample extends Applet{

   /* Constructor is invoked first, when instance of the Applet is created */
   public AppletLifeCycleExample()
   {
   System.out.println("AppletLifeCycleExample()");
   }

    /*
     * init method is called only once, just before displaying
     * applet window
     */
    public void init() {
    super.init();
    System.out.println("init()");
    }

    /*
     * start method is called, whenever applet is displayed(first time)
     * or re displayed(whenever applet window is maximized, or when navigated back)
     */
    public void start() {
    super.start();
    System.out.println("start()");
    }

    /*
     * stop method is called when ever user navigates away or minimizes
     * the applet.
     */
    public void stop() {
    super.stop();
    System.out.println("stop()");
    }

    /* paint method is called every time applet need to be redrawn
     * It is possible to explicitly invoke paint(), using repaint() method
     */
    public void paint(Graphics g) {
    super.paint(g);
    System.out.println("paint()");
    }

    /*
     * destroy method is called only once when this applet is about to be completely destroyed.
     * Add cleanup code to free resources which are initialized
     * during the init method.
     */
    public void destroy() {
    super.destroy();
    System.out.println("destroy()");
    }

}
Output:
AppletLifeCycleExample()
init()
start()
paint()
stop() --minimized applet--
start() --maximized applet--
paint()
stop() -- again minimized applet--
start() -- again maximized applet--
paint()
stop() -- closed applet--
destroy()

You may also like to read:
Advantages of Swings compared to Applet

Leave a Reply