Credits

Sunday, March 6, 2011

Java Applet's Life Cycle

An applet goes through four different states:

  • init ( ) method  - called whenever we initialize variables, define components or add them to our applet container;
  • start ( ) method  - called whenever the user (re)loads the applet;
  • stop ( ) method - called whenever the user leaves the applet;
  • destroy ( ) method - called when you exit the applet and removes the alloted resources.

Using init ( ) method, we can create an applet and if we don't want our applet to behave differently whenever we load or leave from the applet, Java provides the default start ( ), stop ( ) and destroy ( ) and generally, with empty bodies.


The sample program below shows the use of init ( ) and start ( ) and whenever we minimize our applet, the start ( ) method is called.
[+/-] show/hide

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Rose
*/
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class AppletGreetEvent extends Applet implements ActionListener {
JLabel greeting1 = new JLabel("Hello. Who are you?");
JLabel greeting2 = new JLabel();
Font bigFont = new Font("Times New Roman", Font.ITALIC,24);
JButton pressMe = new JButton("Press Me");
JTextField answer = new JTextField(" ",10);

public void init()
{

add(greeting1);
add(answer);
add(pressMe);
answer.requestFocus();// focus for the textfield
pressMe.addActionListener(this);
greeting2.setFont(bigFont);
add(greeting2);
}

public void start()
{ greeting2.setText("This is a sample applet.");}

public void actionPerformed(ActionEvent thisEvent)
{
String name=answer.getText();

greeting2.setText("Hi "+name);
validate();
}
}

AddThis