Java: Applet – Introduction and its life-cycle

We know that Java is used to develop cross-platform applications and we can use Java in almost all types of electronic devices.

The standard Java based applications are used on individual systems; we need to install the standard application on each system from where we want to use the application. Web applications are different; they will install on the servers and can be accessible from clients or web-browsers over the network or Internet. Another types of applications we can create using Java, are applets; applets are small applications, can embed into HTML pages as web-documents and when we request the web-page, applets are downloaded into the client system and execute in the web-browsers. But applets have limited access to resources because of the security reasons. So, applets provide limited functionality to the end-users.

In this article we are going to discuss about how the applet works, what are different phases in the applet life-cycle.

An applet is a special kind of Java program that will run only on Java compatible web-browsers; web-browsers need Java plug-in to run the applets.

Unlike standard Java applications, applets execution doesn’t begin at main() method. So, what would be the entry point for applets? It is in its life-cycle methods; we are going to discuss these life-cycle methods in this article.

Applets are event driven; that means its methods are automatically executed depending on the triggered events; we can call these methods as event handlers. But who will trigger the events? The hosting application. For example: if we embed our applet into an HTML page and if we access this HTML page through a web-browser; web-browser will trigger the applet events. What will happen if no events triggered? Nothing will happen; applet simply waits for an event to trigger.

It is important to understand the Applets’ life-cycle. Once we understand the life-cycle methods; depending on our requirement we can add our code into an appropriate applet life-cycle method.

Following are the applet life-cycle methods:

  • init()
  • start()
  • stop() and
  • destroy()

Lets discuss one-by-one.

init() method is the first method called for any applet. And it is called only once in applet life-cycle. Generally we write initialization code in init() method. That means, assigning the values to data members or variables. Even we add code to establish database connections or some other connections which are required to the applet.

start() method is automatically called after applet initialization (after init() method). We can place our actual code here. This method is invoked by the web-browser to start the applet or to resume the applet. Resume the applet? Yes, applet can be resumed, because it can be stopped by calling its stop() method; whenever required we can restore or resume the applet using start() method. All these things are automatically handled by the host application; so, no need to worry about calling these life-cycle methods.

stop() method is called by the web-browser whenever the user minimizes the applet window, or moves away from the HTML page where the applet is embedded etc.,. Applet suspends it’s execution when stop() method is called; again it resumes the execution when start() method is called. stop() method is called before destroy() method is called; that means before destroying the applet.

destroy() method is called when the applet is going to close or destroy. Usually we will place the code which releases the resources like database connections etc.,. destroy() method is called after the stop() method.

We have discussed enough about applets. Now it is time to write a simple applet.

Step 1. The first step in creation of an applet is, derive it from java.applet.Applet class. So, our class declaration would be like this:

public class MyApplet extends Applet

As Applet class is defined in java.applet package, we need to import Applet class into our code. So, we have to add below import statement into our code:

import java.applet.Applet;

Step 2. As discussed above, applet has its life-cycle methods. Lets implement these life-cycle methods in our program to understand much better when these life-cycle methods are invoked by the hosting application (eg: web-browser). After adding the life-cycle methods our applet code looks like below:

// SampleApplet.java
import java.applet.Applet;

public class SampleApplet extends Applet {

    public void init() {
        System.out.println(“init() method called.”);
    }

    public void start() {
        System.out.println(“start() method called.”);
    }

    public void stop() {
        System.out.println(“stop() method called.”);
    }

    public void destroy() {
        System.out.println(“destroy() method called.”);
    }
}

Step 3. Our program is ready to compile. Lets compile our applet code to generate a Java class file. Below is the command to generate the class file:

javac SampleApplet.java

After successful compilation, this command generates a “SampleApplet.class” file.

Step 4. We are successfully generated our applet class. Now its time to test our applet.

As mentioned above, applets can embed into an HTML page. To embed an applet into an HTML page, we use either <applet> tag or we use <object> tag. In this article we use <applet> tag in our HTML page to embed our applet.

Like other HTML tags, <applet> tag has its attributes; code, width, height etc.,. “code” attribute tells the file name of the applet where its byte code is stored (ie.,. “.class” file name). “width” & “height” are the width and height of the applet window to display on the host application. After embedding applet information into our HTML page; the HTML code looks like below:

<html>
   <body>
       <applet code="SampleApplet.class" width=400 height=300>
       </applet>
    </body>
</html>

Save this HTML code into a file “testapplet.html”.

Step 5. We are ready to test our applet. We can test our applet using web-browser or Java’s “appletviewer” application. Both these needs HTML page to test the applet; we have already created our HTML page “testapplet.html” to test our applet. So, we will use the same here.

Lets test our applet using “appletviewer” application. This is the fast way to test the applets. We need to type below command at command prompt to test our applet:

appletviewer testapplet.html

Observe that, a new window will appear called appletviewer window and start loading our applet into this window. And see the messages displayed on the console window; whenever the event triggered by appletviewer, our applet’s associated life-cycle method will execute and display the relevant message on the console window.

init() method called.
start() method called.
stop() method called.
destroy() method called.

It seems our applet is successfully running. Have you noticed anything different here? Why our messages are not displayed in the appletviewer window; why they are displaying in console window.? To understand this we need to deeply look into Applet class. If we see the Applet class hierarchy in Java documentation it looks like below:

java.lang.Object
– java.awt.Component
– – java.awt.Container
– – – java.awt.Panel
– – – – java.applet.Applet

Observe that Applet class is derived from Panel class and it is derived from Container class and again it is derived from Component class; finally Component class it is derived from parent class of all Java classes, Object class. Panel, Container and Component are the classes in AWT (Abstract Window Toolkit) package; which contains classes to create GUI (Graphical User Interface) based applications.

Usually applets use GUI based user interface instead of console or text-based interface. As Applet class is derived from AWT package classes; we can easily add GUI to our applet. We will do this by simply displaying a text in applet window instead of displaying on console window. To do this, we need to override Container class’s paint method. paint method has a single argument of type Graphics class; with Graphics object we can draw shapes, display images etc.,. We have to add the following method to our applet code:

public void paint(Graphics g) {
    super.paint(g);
    g.drawString("Hello, World!", 50, 50);
}

Remember that we need to include the following import statement also into our applet code; because we are using AWT class Graphics.

import java.awt.Graphics;

We have used Graphics class’s drawString method to display a text “Hello,World!” on the window at the specified location it has been given as “x, y” co-ordinate values as “50, 50”.

AppletViewer - SampleApplet

AppletViewer – SampleApplet

And we also used println statements to display the text on console window; hence we are seeing the results from command prompt, when we open our applet using appletviewer application.

Step 5.1. Now lets test our applet in web-browser.

Just open our “testapplet.html” page in web-browser; depending on the security settings in the browser and Java console, we may encounter some warnings or alerts while opening the applet.

If the security settings allowed to show applets, web-browsers will display our applet; otherwise web-browsers will not display the applets.

Sample applet in web-browser

Sample applet in web-browser

Finally, we have successfully created our applet and placed our code into applet life-cycle methods.

Thank You.

Leave a Reply