Java Applets and its life-cycle

Introduction 

 
This is a program, which can create a graphical user interface to make visible dynamic content in the web browser. It creates a window for the web content visible inside the web browser. The compiled java program can be loaded into the web browser with the help of HTML document. To execute the applet in the web browser it must contain java virtual machine. The applet can deal with presentation logic and business logic. An applet does not have main method as the starting point of the execution.
 

Creation process of an applet

  1. Create a class by inheriting java applet. Applet class.
  2. Override the life cycle method of applet such as init (), start (), stop (), destroy () and provide a presentation with business logic into these methods.
  3. Create an HTML file, which must contain the <Applet> tag to load the applet into the web browser.
  4. Compile the file and load the HTML file into the browser.
  5. Using the applet viewer tool available in JDK can test an applet corresponding HTML file.
The life cycle of an applet
 
It is of five types
  1. Init()
  2. Start()
  3. Paint()
  4. Stop()
  5. Destroy()
Init():- This is a method that initializes the applet with the required components inside it. This method executes only once of the life cycle of an applet.
 
Start():- This method is responsible for activating the applet. This method executes when the applet will be restored or visible in the web browser. This method executes more than once in the life cycle of an applet.
 
Paint():- This method can be used to draw different components or graphical shapes into the applet. This method can be executed repeatedly during the applet execution.
 
Stop():- When an applet will be minimized or made invisible by using the back or forward button of the web browser then the applet will be deactivated by calling this method.
 
Destroy():- When the browser containing the applet will be closed then this method will be called. This method executes only once in the life cycle of an applet.
 
Ex:- lifecycle of an applet
  1. import java.applet.*;  
  2. import java.awt.*;  
  3. public class life extends Applet {  
  4.  public void init() {  
  5.   setBackground(Color.yellow);  
  6.   setFont(new Font("", Font.BOLD, 30));  
  7.   Label lab1 = new Label("lifecycle Applet");  
  8.   add(lab1);  
  9.   System.out.println("Init called");  
  10.  }  
  11.  public void start() {  
  12.   System.out.println("start called");  
  13.  }  
  14.  public void paint(Graphics g) {  
  15.   System.out.println("paint called");  
  16.  }  
  17.  public void stop() {  
  18.   System.out.println("stop called");  
  19.  }  
  20.  public void destroy() {  
  21.   System.out.println("destroy called");  
  22.  }  
  23. }  
Compile
 
javac life.java
appletviewer life.java
  
After closing the applet window stop() is called first and then destroy() method finally execute which is shown below in the console.