An applet is a small program that is designed to be run within a web browser. Applets are written in the Java programming language and are embedded within HTML pages. When a user visits a web page that contains an applet, the applet is downloaded to the user's computer and then executed within the browser.
The life cycle of an applet is controlled by the browser, and consists of four stages: initialization, start, stop, and destruction.
Here is an example of an applet that displays a simple message:
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void init() {
// initialization code goes here
}
public void start() {
// start code goes here
}
public void stop() {
// stop code goes here
}
public void destroy() {
// destruction code goes here
}
public void paint(Graphics g) {
g.drawString("Hello, world!", 20, 20);
}
}
In this example, the HelloWorld class extends the Applet class and overrides four methods: init(), start(), stop(), and destroy(). These methods are called by the browser at different points in the applet's life cycle:
- init(): This method is called when the applet is first loaded. It is used to perform any initialization that needs to be done before the applet can be started.
- start(): This method is called after init() and is used to start the applet. This method may be called multiple times if the user leaves the page and then returns to it.
- stop(): This method is called when the applet is stopped, either because the user has navigated away from the page or because the applet has encountered an error.
- destroy(): This method is called when the applet is destroyed, either because the user has closed the browser or because the browser has encountered an error.
- The paint() method is also overridden and is used to draw graphics on the applet's canvas. In this example, the method simply draws the message "Hello, world!" at the coordinates (20, 20).
Overall, the life cycle of an applet is managed by the browser and is controlled by the methods that are overridden by the applet's code. By understanding the applet life cycle, developers can create more robust and reliable applets that work well within a web browser environment.
No comments:
Post a Comment
If you have any doubts, please let me know