Building Applet Code


To building the applet code two classes of java library are essential namely Applet and Graphics.

The Applet class is contained in java.applet package provides life and beehaviour to the applet through its methods such as int(), start() and paint().

Unlike with applications, where java calls the main() method directly to initiate the execution of the program, when an applet is loaded java automatically calls a series of Applet class methods for starting running and stopping the applet code.

The Applet class therefore maintains the life cycle of an applet.

To display the result of the applet code, the paint() method of the Applet class is called up.

The output may be test, graphics, or sound.

The syntax of paint() method which requires a Graphic object as an argument, is defined as follows

public void paint(Graphics g)

This requires that the applet code imports the java.awt package that contain the Graphic class.

All output operations of an applet are performed using the methods defined in the graphics class.

The general format of applet code is as following:

import java.awt.*;
import java.applet.*;
.........................
.........................
public class applet classname extends Applet
{
.................................
................................ //statements
................................
public void  paint(Graphics g)
{
..........................
..........................//Applet operations code
.........................
}
......................
.....................
}

Building Applet Code

//HelloApplet.java
import java.applet.Applet;
import java.awt.*;
  public class HelloApplet extends Applet
  { 
    public void paint(Graphics g)
    {
      g.drawString ("Welcome to Applet Tutorial !",100, 100);
    }
  }

Embedding Applet in HTML (Web Page)

<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Java Applet on the Web!</h1>
<APPLET CODE="HelloApplet.class" width=500 height=400>
</APPLET>
</body>
</HTML>

Share this article on