CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

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 accessed from clients or web-browsers over the network or Internet.

Another type of application 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 executed in the web-browsers. But, applets have limited access to resources because of security reasons. So, applets provide limited functionality to the end-users.

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

What is a Java Applet?

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

Unlike standard Java applications, applets execution doesn’t begin with 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 their methods are automatically executed depending on the triggered events; we can call these methods event handlers. But, who will trigger these events? The hosting application will trigger these events. For example: if we embed our applet into an HTML page and if we access this HTML page through a web browser; the web browser will trigger the applet events. What will happen if no events are triggered? Nothing will happen; the applet simply waits for an event to trigger.

An Applet life-cycle

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()

Let’s discuss each of these methods, one-by-one.

init() method

init() method is the first method called for any applet. And it is called, only once in applet’s life-cycle. Generally, we write initialization code in the 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

This 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, applets can be resumed, because they can be stopped by calling their stop() method; whenever required we can restore or resume the applet using the 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

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

destroy() method

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

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

Writing a simple Java Applet

Step 1. The first step in the 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 the Applet class into our code. So, we have to add the below import statement into our code:

import java.applet.Applet;

Step 2. As discussed above, the applet has its life-cycle methods. Let’s 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. Let’s 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 it’s 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” is 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 a web browser or Java’s “appletviewer” application. Both these need an 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.

Let’s test our applet using “appletviewer” application. This is the fast way to test the applets. We need to type the below command at the 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 is 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 displayed in the 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 a parent class of all Java classes, Object class. The 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 a console or text-based interface. As the 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 the applet window instead of displaying it on the console window. To do this, we need to override the Container class’s paint method. The 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 the console window; hence we are seeing the results from the 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.

Java Applet – Introduction and its life-cycle

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top