Applet Program in Java

An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side. In an HTML page, an applet can be embedded using the applet or object tag. To furnish dynamic content on a website, Java applets are used. The applet program in Java demonstrates how to use applets in the program. A Java applet does not contain the main method. Let’s discuss applet in brief.

Applet’s Life Cycle

Following methods are involved in the life cycle of an applet.

  • init(): The init() method does the initialization of variables. When the applet is loaded, the method is called for doing the initialization work. Since, the applet is loaded only once, therefore, the init() method is also called only once.
  • start(): The start() method is called after the init() method has  done its job. The start() method is responsible for restarting an applet that has been stopped. Every time an applet’s HTML content is rendered on the screen, the start() method is called. For example, when a user moves from an applet’s HTML window to some different window and then comes back to the applet’s HTML window again, the start() method is invoked.
  • paint(): Whenever the output is displayed by the applet, the paint() method is called. For example, when the applet’s window is first minimized, then restored, then the paint() method gets called that redraws the output. The paint() method is also invoked when the applet starts its execution. This is done to render the output on the screen.
  • stop(): When the user moves from the applet’s HTML window to some different window,  the stop() method is called. It suspends the threads when the applet invisible. When the user comes back then those suspended thread starts by invoking the start() method and the applet’s output is again visible.
  • destroy(): For complete removal of applets from memory, the destroy() method is called. Therefore, any resources occupied by the applets should be freed up at this point in time. Thus, before calling the destroy() method, it is necessary to call the stop() method for the suspension of threads.

Java Applet Program

The following program shows how to create various geometrical shapes using applets.

FileName: AppletExample.java

For Execution:

To execute the above written applet program in a web browser, an HTML file is required. Inside the HTML file, add the following code snippet.

The width and height supplied in the applet tag that determines the display area. \

Explanation: The public access specifier for the class AppletExample is due to the fact that the outer environment needs to access the above program and any other access specifier reduces the visibility. Whatever needs to be painted is written inside the paint() method. When the AWT(Abstract Window Toolkit) invokes the paint() method, the Graphics parameter is configured, for drawing, with an appropriate state.

Pin It on Pinterest

Share This