Credits

Saturday, March 13, 2010

Java Applet's Life Cycle

Any Java Applet goes through four stages: initialization, start, stop and destroy. When an applet is run, it executes initialization once, then proceeds to  start method. However, should we minimize the applet, it stops its execution, then if restored, it goes to execute start again. The destroy method is only run if one chooses to close fully the window.


Find below a sample program to demonstrate the life cycle of an applet. 

[+/-] show/hide



import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AppletLifeCycle extends Applet implements ActionListener {
Label messageInit = new Label("init ");
Label messageStart = new Label("start ");
Label messageDisplay = new Label("display ");
Label messageAction = new Label("action ");
Label messageStop = new Label("stop ");
Label messageDestroy = new Label("destroy ");
Button pressButton = new Button("Press");

int countInit,countStart,countDisplay,countAction, countStop,countDestroy;

public void init()
{++countInit;
add(messageInit);
add(messageStart);
add(messageDisplay);
add(messageAction);
add(messageStop);
add(messageDestroy);
add(pressButton);
pressButton.addActionListener(this);
display();
}

public void start()
{
++countStart;
display();
}

public void display()
{
++countDisplay;
messageInit.setText("init "+countInit);
messageStart.setText("start "+countStart);
messageDisplay.setText("display "+countDisplay);
messageAction.setText("action "+countAction);
messageStop.setText("stop "+countStop);
messageDestroy.setText("destroy "+countDestroy);

}

public void stop()
{
++countStop;
display();
}
public void destroy()
{
++countDestroy;
display();

}


public void actionPerformed(ActionEvent e)
{
++countAction;
display();
}
}

AddThis