Skip to main content

Practical-46

Create an applet that use init(),start(),stop() and destroy() methods of applet.

Answer

Introduction

An applet is a small program written in the Java programming language that is designed to be loaded directly from a web browser and executed on the client’s machine. Applet programs use the override methods init(), start(), stop(), and destroy() to let the applet code respond to various events. The init() method is used to create and initialize the applet when it is first loaded into the browser, the start() method is used to begin the action, the stop() method is used to halt the applet’s action (if necessary), and the destroy() method is used to destroy the applet.

Code

//Create an applet that use init(),start(),stop() and destroy() methods of applet. 
import java.awt.*;
import java.applet.*;

public class MyFirstApplet extends Applet
{

public void init()
{
// code to execute when applet is first loaded
System.out.println("My First Applet!");
}

public void start()
{
// code to execute when applet starts running
System.out.println("Applet Started");
}

public void stop()
{
// code to execute when applet is stopped
System.out.println("Applet Stopped");
}
public void destroy()
{
// code to execute when applet is destroyed
System.out.println("Applet Destroyed");
}

public void paint(Graphics g)
{
// code to execute when applet is ready to paint
}

}

Output

My First Applet!
Applet Started
Applet Stopped
Applet Destroyed

Explanation

This code creates an applet class and implements the required init(), start(), stop(), and destroy() methods. The init() method indicates that the applet is being loaded for the first time, the start() method indicates that the applet is ready to start running, the stop() method indicates that the applet should stop running, and the destroy() method indicates that the applet is being closed and should be removed from the browser.