Java Applet Basics
An Applet is a Java program that typically runs within a Java-enabled web browser. Because it has full support for the Java API, an Applet is a fully functional Java application.
The following are important differences between standalone Java applications and applet programs:
- In Java, the Applet class inherits from the java.applet.Applet class.
- The Applet class does not define a main(), so an Applet program does not invoke the main() method.
- An Applet is designed to be embedded within an HTML page.
- When a user visits an HTML page containing an Applet, the Applet's code is downloaded to the user's machine.
- To view an Applet, a JVM is required. The JVM can be a plugin for the web browser or a standalone runtime environment.
- The JVM on the user's machine creates an instance of the Applet class and invokes various methods during the Applet's lifecycle.
- Applets have strict security rules enforced by the web browser, and the Applet's security mechanism is known as sandbox security.
- Additional classes required by the Applet can be downloaded in the form of Java Archive (JAR) files.
Applet Lifecycle
The four methods in the Applet class provide a framework on which you can develop your applet:
- init: This method is intended for any initialization needed by your Applet. It is called after the param tags within the Applet tag are processed.
- start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the Applet.
- stop: This method is automatically called when the user moves off the page containing the Applet. It can be called repeatedly in the same Applet.
- destroy: This method is called only when the browser normally shuts down. Since an Applet is only valid on an HTML page, you should not leave any resources behind after the user leaves the page containing the Applet.
- paint: This method is called immediately after the start() method, or when the Applet needs to be redrawn in the browser. The paint() method actually inherits from java.awt.
"Hello, World" Applet:
Below is a simple Applet program HelloWorldApplet.java:
HelloWorldApplet.java File Code:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World", 25, 50);
}
}
These import statements bring the following classes into our Applet class:
java.applet.Applet.
java.awt.Graphics.
Without these import statements, the Java compiler would not recognize the Applet and Graphics classes.
Applet Class
Every Applet is a subclass of the java.applet.Applet class. The base Applet class provides methods that can be called by derived classes to obtain information about the browser context and services.
These methods do the following:
- Obtain the parameters of the Applet
- Obtain the network location of the HTML file containing the Applet
- Obtain the network location of the Applet class directory
- Print status information to the browser
- Retrieve an image
- Retrieve an audio clip
- Play an audio clip
- Resize the Applet
In addition, the Applet class provides an interface for the Viewer or browser to obtain information about the Applet and to control the execution of the Applet.
The Viewer may:
- Request information about the Applet's author, version, and copyright
- Request a description of the parameters recognized by the Applet
- Initialize the Applet
- Destroy the Applet
- Start the execution of the Applet
- Stop the execution of the Applet
The Applet class provides default implementations of these methods, which can be overridden when needed.
The "Hello, World" Applet is written according to the standard. The only method that is overridden is the paint method.
Invoking an Applet
An Applet is a Java program that typically runs within a Java-enabled web browser. Because it has full support for the Java API, an Applet is a fully functional Java application.
The <applet>
tag is the basis for embedding an Applet in an HTML file. Below is an example of calling a "Hello World" applet;
HTML Code:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note: You can refer to the HTML Applet tag for more information on how to call an applet from HTML.
The attributes of the <applet>
tag specify the Applet class to be run. The width and height are used to specify the initial size of the Applet's display panel. The Applet must be closed with the </applet>
tag.
If the Applet accepts parameters, the parameter values need to be added within the <param>
tag, which is located between the <applet>
and </applet>
tags. The browser ignores the text and other tags between the applet tags.
Browsers that do not support Java cannot execute <applet>
and </applet>
. Therefore, anything displayed between the tags and not related to the applet is visible in browsers that do not support Java.
The Viewer or browser looks for the compiled Java code at the location of the document. To specify the path of the document, use the codebase
attribute of the <applet>
tag.
As shown below:
<applet codebase="http://amrood.com/applets"
code="HelloWorldApplet.class" width="320" height="120">
If the Applet is in a package rather than the default package, the package must be specified in the code
attribute, for example:
<applet code="mypackage.subpackage.TestApplet.class"
width="320" height="120">
#
Getting Applet Parameters
The following example demonstrates how to use an Applet response to set parameters specified in the document. The Applet displays a black checkerboard pattern and a second color.
The second color and the size of each column are specified by parameters in the document.
CheckerApplet gets its parameters in the init()
method. It is also possible to get parameters in the paint()
method. However, it is more convenient and efficient for the Applet to get the values and save the settings once it starts, rather than getting the values every time it refreshes.
The Applet viewer or browser calls the init()
method each time the Applet runs. After loading the Applet, the Viewer immediately calls the init()
method (Applet.init() does nothing), overriding the default implementation to add some custom initialization code.
The Applet.getParameter() method retrieves the parameter value by giving the parameter name. If the value obtained is numeric or other non-character data, it must be parsed from a string.
The following is a modified version of CheckerApplet.java:
CheckerApplet.java File Code:
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// Initialize default size
public void init () {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Below is the init()
method and the private parseSquareSize()
method of the CheckerApplet class:
public void init ()
{
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
setForeground(fg);
}
private void parseSquareSize(String param) {
if (param == null) return;
try {
squareSize = Integer.parseInt(param);
} catch (Exception e) {
// Keep default value
}
}
This Applet calls the parseSquareSize()
method to parse the squareSize
parameter. The parseSquareSize()
method calls the library method Integer.parseInt()
, which parses a string into an integer. When the parameter is invalid, Integer.parseInt()
throws an exception.
Therefore, the parseSquareSize()
method also catches exceptions and does not allow the Applet to accept invalid input.
The Applet calls the parseColor()
method to parse the color parameter into a Color
value. The parseColor()
method performs a series of string comparisons to match the parameter value with predefined color names. You need to implement these methods to make the Applet work.
Specifying Applet Parameters
The following example is an HTML file that embeds the CheckerApplet
class. The HTML file specifies two parameters for the applet using the <param>
tag.
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
</html>
Note: Parameter names are case-insensitive.
Converting an Application to an Applet
Converting a graphical Java application (i.e., an application that uses AWT and is launched with the java launcher) to an applet embedded in a web page is straightforward.
Here are the steps to convert an application to an applet:
Write an HTML page with tags that load the applet code.
Write a subclass of the
JApplet
class and set it to public. Otherwise, the applet cannot be loaded.Eliminate the
main()
method from the application. Do not construct a frame window for the application, as it will be displayed in the browser.Move the initialization code from the constructor of the frame window in the application to the
init()
method of the applet. You do not need to explicitly construct an applet object; the browser will instantiate one by callinginit()
.Remove calls to
setSize()
. The size of the applet is set via the width and height parameters in the HTML file.Remove calls to
setDefaultCloseOperation()
. An applet cannot be closed; it terminates when the browser exits.If the application calls
setTitle()
, remove those calls. An applet cannot have a title bar. (You can, however, give the web page itself a title via the HTML title tag.)Do not call
setVisible(true)
; applets are automatically displayed.
Event Handling
The Applet class inherits many event-handling methods from the Container class. The Container class defines several methods, such as processKeyEvent()
and processMouseEvent()
, for handling specific types of events, and a catch-all method called processEvent()
.
To respond to an event, an applet must override the appropriate event-handling method.
ExampleEventHandling.java File Code:
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
public class ExampleEventHandling extends Applet
implements MouseListener {
StringBuffer strBuffer;
public void init() {
addMouseListener(this);
strBuffer = new StringBuffer();
This is an example of an applet that handles events and displays images. Here is the English translation of the provided text:
public void init() {
addItem("initializing the applet ");
}
public void start() {
addItem("starting the applet ");
}
public void stop() {
addItem("stopping the applet ");
}
public void destroy() {
addItem("unloading the applet");
}
void addItem(String word) {
System.out.println(word);
strBuffer.append(word);
repaint();
}
public void paint(Graphics g) {
// Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
// Display the string inside the rectangle.
g.drawString(strBuffer.toString(), 10, 20);
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
}
}
To call this applet:
<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
</applet>
<hr>
</html>
When initially run, the applet displays "initializing the applet. Starting the applet." Then, when you click inside the rectangle, it shows "mouse clicked".
Displaying Images
Applets can display images in formats like GIF, JPEG, BMP, etc. To display an image in an applet, you need to use the drawImage()
method of the java.awt.Graphics
class.
Here is an example demonstrating all the steps to display an image:
ImageDemo.java file code:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
public void paint(Graphics g)
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
To invoke this applet:
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</applet>
<hr>
</html>
Playing Audio
Applets can play audio by using the AudioClip interface from the java.applet package. The AudioClip interface defines three methods:
public void play(): Plays the audio clip once from the beginning.
public void loop(): Plays the audio clip in a loop.
public void stop(): Stops playing the audio clip.
To obtain an AudioClip object, you must call the getAudioClip() method of the Applet class. This method returns immediately regardless of whether the URL points to a real audio file.
The audio file is downloaded only when it is about to be played.
The following example demonstrates all steps to play audio:
AudioDemo.java file code:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
{
private AudioClip clip;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null)
{
audioURL = "default.au";
}
try
{
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
{
if(clip != null)
{
clip.stop();
}
}
}
To invoke this applet:
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="0" height="0">
<param name="audio" value="test.wav">
</applet>
<hr>
You can use the test.wav on your computer to test the above example.