Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java, applets are small applications that run within a web browser or applet viewer, providing interactive user interfaces. Understanding the applet life cycle is crucial for developers working with applets, as it defines how an applet is loaded, initialized, executed, and destroyed within the Java environment.
Java Applets were created as a way to run Java code within a web browser, allowing developers to create complex graphical user interfaces and animations that were not possible with HTML alone. The applet life cycle in Java is the process that an applet goes through, from the time it is loaded by the web browser to the time it is unloaded.
Hierarchy of Applet in Java
The hierarchy of Applet in Java can be depicted as follows:
Object: At the root of the Java class hierarchy is the Object class. Every class in Java is a direct or indirect subclass of Object. It provides basic functionalities that are common to all objects in Java, such as toString(), equals(), and hashCode().
Component: The Component class is an abstract base class for all AWT (Abstract Window Toolkit) components. It represents visual elements that can be added to a graphical user interface (GUI). Examples of components include buttons, text fields, labels, and checkboxes. Component provides methods for managing properties and events common to all GUI components.
Container: The Container class is a subclass of Component and represents a generic container for holding other components. Containers can include frames, panels, and applets. They provide a way to organize and manage the layout of GUI components within a window.
Panel: The Panel class is a lightweight container that extends Container. It is used to group and organize other components within a window. Panels can be added to frames, applets, or other containers to create complex layouts. They are commonly used for organizing GUI elements into sections or groups.
Applet: The Applet class is a subclass of Panel and represents the base class for creating applets in Java. Applets are small Java programs that run within a web browser. They provide interactive content and are typically used for creating animations, games, and multimedia applications on the web.
JApplet: The JApplet class is a subclass of Applet and is part of the Swing framework, which is Java's GUI toolkit. JApplet provides additional functionality and features compared to the basic Applet class. It allows developers to create applets with more sophisticated user interfaces using Swing components such as JButton, JLabel, JTextField, and others.
Methods of Applet Life Cycle
The functions involved in the Applet life cycle in Java are:
1. init()
Syntax
public void init()
{
// To initialize objects
}
Called when the applet is first loaded into memory.
Initializes the applet and sets its default values, such as creating objects and initializing variables.
Called only once during the applet life cycle, at the start.
2. start()
Syntax
public void start()
{
// To start the applet code
}
Called immediately after init() method.
Begins the execution of the applet, such as starting threads or animations.
Can be called multiple times if the applet is paused and resumed (e.g., when a user navigates back to the page).
3. paint (Graphics g)
Syntax
public void paint(Graphics graphics)
{
// Any shape's code
}
Called whenever the applet needs to be redrawn or updated on the screen.
Responsible for rendering graphics, shapes, or images onto the applet’s window.
Can be called multiple times when the applet is resized or when the screen needs to be refreshed.
4. stop()
Syntax
public void stop()
{
// To stop the applet code
}
Called when the applet is no longer visible or active (e.g., when the user navigates away from the applet).
Stops ongoing tasks like animations or threads.
Releases any resources that the applet was using, such as halting network connections or stopping background tasks.
5. destroy()
Syntax
public void destroy()
{
// To destroy the applet
}
Called when the applet is being removed from memory, either due to the browser being closed or applet termination.
Responsible for cleaning up resources the applet was using, such as closing files, database connections, or stopping threads.
This method is called only once in the applet’s life cycle, just before the applet is unloaded from memory.
Working of Applet Life Cycle
The working Java Applet Life cycle is as follows:
The Applet life cycle is managed by the Java plug-in program
An applet is a Java application implemented in any web browser and works on the client side. It does not contain the main() method as it runs in the browser. It is therefore created to be placed on an HTML page
The awt.Component class consists of the paint() method
The applet.Applet class consist of start(), init(), destroy(), stop() methods
If we want to make a class an Applet class in Java, we are required to extend the Applet
Whenever an applet is created, we create an instance of the existing Applet class. And therefore, we can use all the methods of that class
Syntax of entire Applet Life Cycle in Java
Below is the syntax of the code that shows the applet life cycle in Java:
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
// Initialization state
public void init() {
// This method is called only once, when the Applet is first loaded into memory.
// Initialize the Applet and set its default values.
}
public void start() {
// This method is called after the init() method.
// Start the execution of the Applet and perform all necessary tasks.
}
// Running state
public void paint(Graphics g) {
// This method is called whenever the Applet needs to be painted on the screen.
// Perform all necessary drawing tasks here.
}
// Idle state
public void stop() {
// This method is called when the Applet is stopped.
// Stop the execution of the Applet and release any resources that it was using.
}
// Dead state
public void destroy() {
// This method is called when the Applet is being removed from memory.
// Release all of the resources used by the Applet.
}
}
Code Implementation of Applet Life Cycle in Java
Below are a few examples that demonstrate the applet life cycle methods in action.
Example 1: Simple Applet with init(), start(), paint(), stop(), and destroy() Methods
import java.applet.Applet;
import java.awt.Graphics;
public class AppletLifeCycleExample1 extends Applet {
// init() method: Initializes the applet
public void init() {
System.out.println("Applet Initialized");
}
// start() method: Starts the applet execution
public void start() {
System.out.println("Applet Started");
}
// paint() method: Responsible for drawing content
public void paint(Graphics g) {
g.drawString("Hello, this is an Applet!", 50, 50);
}
// stop() method: Stops the applet execution
public void stop() {
System.out.println("Applet Stopped");
}
// destroy() method: Cleans up resources
public void destroy() {
System.out.println("Applet Destroyed");
}
}
Output:
Console Output will show the following as the applet runs:
Applet Initialized (when the applet is loaded)
Applet Started (when the applet starts)
On the applet's window, you will see: "Hello, this is an Applet!"
Applet Stopped (when the applet is stopped)
Applet Destroyed (when the applet is removed from memory)
This applet demonstrates the basic life cycle methods that are invoked during the execution of an applet.
Example 2: Applet with Animation Using init(), start(), paint(), and stop()
import java.applet.Applet;
import java.awt.Graphics;
public class AnimationApplet extends Applet {
private int x = 0;
// init() method: Initialize applet settings
public void init() {
setSize(300, 200);
System.out.println("Applet Initialized");
}
// start() method: Starts animation
public void start() {
System.out.println("Animation Started");
Thread animationThread = new Thread(() -> {
while (x < 300) {
x += 10;
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
animationThread.start();
}
// paint() method: Draws the moving object
public void paint(Graphics g) {
g.fillOval(x, 100, 30, 30); // Draw a moving circle
}
// stop() method: Stops the animation
public void stop() {
System.out.println("Animation Stopped");
}
}
Output:
Console Output will show:
Applet Initialized (when the applet is loaded)
Animation Started (when the animation starts)
A moving circle will be displayed across the applet window.
Once the applet stops, Animation Stopped will be printed.
Example 3: Applet with destroy() Method Demonstrating Resource Cleanup
import java.applet.Applet;
import java.awt.Graphics;
public class ResourceCleanupApplet extends Applet {
// init() method: Initialize resources
public void init() {
System.out.println("Applet Initialized: Resources Loaded");
}
// paint() method: Display message
public void paint(Graphics g) {
g.drawString("Applet is running...", 50, 50);
}
// destroy() method: Releases resources
public void destroy() {
System.out.println("Applet Destroyed: Resources Released");
}
}
Output:
Console Output will show:
Applet Initialized: Resources Loaded (when the applet is initialized)
Applet Destroyed: Resources Released (when the applet is removed from memory)
Frequently Asked Questions
What are the phases of applet lifecycle?
The phases of the applet lifecycle are the initialization, start, stop, and destruction phases, which are used for initialization, to start, stop, and for destruction, respectively. These phases tell about the basic lifecycle of applet.
What is the difference between init and start in applet?
In an applet, the init() method is called once to initialize the applet, typically used for setting up resources. The start() method is invoked after init(), signaling the applet to begin execution or resume after being paused.
Why are applets no longer widely used?
Applets are no longer widely used due to security concerns, limited browser support, and the advent of modern web technologies like HTML5, JavaScript, and CSS, which offer better performance and compatibility across platforms.
Are applets still supported in Java?
No, applets are no longer supported in modern Java versions. Starting from Java 9, the applet API has been deprecated, and browsers have removed support for Java plugins, making applets obsolete for web development.
How does an applet differ from a standalone application?
An applet runs within a web browser or applet viewer, relying on the browser's runtime environment. A standalone application, on the other hand, runs independently on a user's system without the need for a browser or external viewer.
Conclusion
The applet life cycle in Java is a crucial concept for understanding how applets are executed and managed within a browser or applet viewer. By mastering the key methods — init(), start(), paint(), stop(), and destroy() — developers can effectively control the initialization, execution, rendering, and cleanup of applets. Despite their decline in popularity with the rise of modern web technologies, applets remain an important part of Java's legacy, providing insights into event-driven programming and graphical interface design.
Hope this article helped you to have a better understanding of the applet life cycle in Java, the different stages involved in the creation of an applet, and how they interact with each other.