Introduction
An Applet is a small Java program that runs inside a web browser or an applet viewer. Unlike a standalone Java application that begins execution at the main() method, an applet is embedded inside an HTML page and is executed by the browser's Java plug-in. Applets were historically used to add interactive features — animations, games, graphs, and client-side validation — to web pages at a time when JavaScript was still primitive. Although modern browsers have deprecated the Java plug-in and applets are largely obsolete in production, the concept remains an important part of the Pokhara University BCA syllabus because it demonstrates the Java component lifecycle, the AWT graphics model, and event-driven programming.
This chapter covers the architecture of applets, their lifecycle methods, the difference between applets and applications, how to embed applets in HTML, how to draw graphics using the Graphics class, how to pass parameters, and how to handle events. Example code and diagrams are provided throughout so that you can practice writing, compiling, and viewing applets using the appletviewer utility that ships with the JDK.
Applet versus Application
A Java application is a standalone program that runs directly on the Java Virtual Machine (JVM) from the command line. Execution begins at the public static void main(String[] args) method, and the program runs with full access to the host operating system — it can open files, connect to networks, and spawn processes as permitted by the OS user.
A Java applet, in contrast, is a component designed to be embedded inside another program — typically a web browser. Applets do not have a main() method. Instead, they extend java.applet.Applet (or javax.swing.JApplet for Swing-based applets) and override lifecycle methods that the browser calls at appropriate times. Applets run inside a sandbox that restricts access to the local file system and network, which made them a popular delivery mechanism for untrusted code in the late 1990s.
| Aspect | Application | Applet |
|---|---|---|
| Execution | Runs standalone from command line or IDE | Runs inside a browser or appletviewer |
| Entry point | main() method | Lifecycle methods: init(), start(), stop(), destroy() |
| Base class | No mandatory base class | Must extend Applet or JApplet |
| Security | Full access to system resources | Runs in a restricted sandbox |
| Deployment | JAR file run by JVM | Embedded in HTML using <applet> or <object> tag |
| GUI | Must create frame manually | Browser provides the drawing surface |
The Applet Class Hierarchy
Every applet class extends java.applet.Applet, which itself extends java.awt.Panel, which extends Container, which extends Component, which extends Object. This hierarchy means an applet is fundamentally an AWT container — it can hold buttons, text fields, labels, and other components, and it can be painted on using the Graphics class. Swing applets extend javax.swing.JApplet, which extends Applet and adds support for Swing components, root panes, and the Swing look and feel.
Applet Lifecycle
The applet lifecycle is governed by four methods that the browser calls at well-defined moments. Understanding these methods is essential for writing correct applets and is a frequent exam question. The methods are init(), start(), stop(), and destroy(). In addition, the paint(Graphics g) method is called whenever the applet needs to redraw itself — for example, when the browser window is resized, uncovered by another window, or when repaint() is called programmatically.
init()
The init() method is called exactly once, when the applet is first loaded into the browser. Use this method to perform one-time initialization: reading parameters from the HTML, loading images or sound files, creating UI components, and setting up layout managers. Anything that does not change for the lifetime of the applet belongs in init().
start()
The start() method is called after init() and every time the user returns to the web page containing the applet (for example, by pressing the Back button). Use this method to start animations, timers, and background threads. If the applet uses a Thread for animation, you typically create and start the thread in start().
stop()
The stop() method is called whenever the user leaves the page (by navigating away or switching tabs) and just before destroy(). Use this method to stop animations and suspend background threads so the applet does not consume CPU while the user is not looking at it. Always stop what you start — failing to do so is a common source of resource leaks.
destroy()
The destroy() method is called exactly once, when the browser is about to unload the applet permanently (typically when the browser is closed). Use this method to release any resources that stop() did not release — open network connections, file handles, or native resources.
paint(Graphics g)
The paint() method is inherited from Component and is called by the AWT event thread whenever the applet's visible surface needs to be redrawn. The argument is a Graphics object that provides methods such as drawString, drawLine, drawRect, fillOval, and setColor. Never call paint() directly — instead call repaint(), which schedules a call to update(), which calls paint().
First Applet Example
import java.applet.Applet;
import java.awt.Graphics;
public class HelloApplet extends Applet {
public void init() {
System.out.println("init called");
}
public void start() {
System.out.println("start called");
}
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50);
}
public void stop() {
System.out.println("stop called");
}
public void destroy() {
System.out.println("destroy called");
}
}Save this as HelloApplet.java and compile with javac HelloApplet.java. Then create an HTML file to host the applet:
<html>
<body>
<applet code="HelloApplet.class" width="300" height="200"></applet>
</body>
</html>Run it with appletviewer hello.html. The appletviewer ignores the HTML around the <applet> tag and displays only the applet itself — it is the recommended way to test applets in the JDK since modern browsers no longer support the Java plug-in.
The <applet> HTML Tag
The <applet> tag embeds an applet in an HTML page. Its attributes include code (the class file), width and height (dimensions in pixels), codebase (the directory containing the class file), and archive (a JAR file containing the applet classes). Nested <param> tags pass named parameters to the applet, which the applet reads using getParameter(name).
<applet code="Greeting.class" width="400" height="100">
<param name="message" value="Welcome to Java Applets">
<param name="color" value="blue">
</applet>The modern HTML specification has deprecated the <applet> tag in favor of <object>. Both tags support essentially the same attributes.
Reading Parameters with getParameter()
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Greeting extends Applet {
private String message;
private Color color;
public void init() {
message = getParameter("message");
if (message == null) message = "Default message";
String c = getParameter("color");
color = "blue".equalsIgnoreCase(c) ? Color.BLUE : Color.BLACK;
}
public void paint(Graphics g) {
g.setColor(color);
g.drawString(message, 20, 50);
}
}The getParameter method returns the value of the named parameter as a String, or null if the parameter was not specified. Always handle the null case to avoid NullPointerException.
Drawing with the Graphics Class
The java.awt.Graphics class provides the drawing API used inside paint(). Common methods include:
drawString(String s, int x, int y)— draws text at the specified baselinedrawLine(int x1, int y1, int x2, int y2)— draws a linedrawRect(int x, int y, int w, int h)andfillRect(...)— outlined or filled rectanglesdrawOval(int x, int y, int w, int h)andfillOval(...)— outlined or filled ovalsdrawPolygon(int[] xs, int[] ys, int n)andfillPolygon(...)drawArc(int x, int y, int w, int h, int start, int extent)setColor(Color c)andsetFont(Font f)
Coordinates in AWT are measured from the top-left corner of the applet, with x increasing to the right and y increasing downward.
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(10, 10, 100, 50);
g.setColor(Color.BLUE);
g.drawOval(120, 10, 80, 80);
g.setColor(Color.GREEN);
g.drawLine(0, 120, 300, 120);
g.setColor(Color.BLACK);
g.setFont(new Font("Serif", Font.BOLD, 18));
g.drawString("Shapes Demo", 80, 150);
}Animation Example
Animation in applets is typically done by starting a thread in start(), updating state periodically, and calling repaint() to request redraws. The Thread.sleep() method controls frame rate.
import java.applet.Applet;
import java.awt.*;
public class MovingBall extends Applet implements Runnable {
private int x = 0;
private Thread t;
private volatile boolean running;
public void start() {
running = true;
t = new Thread(this);
t.start();
}
public void stop() { running = false; }
public void run() {
while (running) {
x = (x + 5) % getWidth();
repaint();
try { Thread.sleep(50); } catch (InterruptedException e) { break; }
}
}
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(x, 50, 30, 30);
}
}Notice how stop() sets a volatile flag to signal the thread to exit. Failing to stop the animation thread would leave it running after the user navigates away from the page, wasting CPU time.
Event Handling in Applets
Because the Applet class extends Panel, it is a Component and can register listeners for mouse and keyboard events. Event handling uses the standard AWT delegation model: the applet registers a listener object, and the AWT invokes the listener method whenever the event occurs.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class ClickCounter extends Applet implements MouseListener {
private int clicks = 0;
public void init() { addMouseListener(this); }
public void paint(Graphics g) {
g.drawString("Clicks: " + clicks, 20, 20);
}
public void mouseClicked(MouseEvent e) { clicks++; repaint(); }
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}To avoid implementing all five methods of MouseListener, you can instead extend MouseAdapter, which provides empty default implementations, and override only the methods you need.
JApplet and Swing
Swing applets extend javax.swing.JApplet, which is very similar to Applet but uses Swing components instead of AWT. The key difference is that Swing components are drawn into a root pane — you add components to getContentPane() rather than directly to the applet.
import javax.swing.*;
import java.awt.*;
public class SwingGreeting extends JApplet {
public void init() {
JPanel panel = new JPanel();
panel.setBackground(Color.LIGHT_GRAY);
panel.add(new JLabel("Hello from Swing!"));
panel.add(new JButton("Click me"));
setContentPane(panel);
}
}Applet Security Sandbox
Applets downloaded from the internet run inside a security sandbox enforced by the SecurityManager. Restrictions include: no reading or writing of local files, no starting of native processes, no network connections except back to the server the applet was loaded from, and no loading of native libraries. A signed applet whose certificate the user trusts can request additional privileges. The sandbox is what historically made applets safe to embed in web pages, but it also made them cumbersome for tasks that required local access.
Methods Inherited from Applet Class
In addition to the lifecycle methods, the Applet class provides many useful utility methods:
getDocumentBase()— URL of the HTML document containing the appletgetCodeBase()— URL of the directory containing the applet's class filesgetImage(URL url, String name)— load an imagegetAudioClip(URL url, String name)— load a sound clipshowStatus(String msg)— display a message in the browser status bargetAppletContext()— access the browser environmentisActive()— true betweenstart()andstop()
Converting Applet to Application
Since applets have essentially disappeared from production, it is common to convert an applet into a standalone application by wrapping it in a JFrame. Give the class a main() method that creates a frame, sets its size, creates an instance of the applet, calls init() and start() manually, and adds the applet to the frame's content pane.
public static void main(String[] args) {
JFrame frame = new JFrame("Applet as App");
SwingGreeting app = new SwingGreeting();
app.init();
app.start();
frame.add(app);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}Common Mistakes
- Forgetting to override
paint()— the applet area will appear blank - Calling
paint()directly instead ofrepaint() - Not stopping threads in
stop()— causes resource leaks - Reading parameters in
paint()rather thaninit()— performance issue and may be called before the page loads - Using Swing components without calling
setContentPane() - Assuming
init()will always be called — in appletviewer it is, but unit tests require manual invocation
Summary
Applets are small Java programs that run inside a web browser. Every applet extends java.applet.Applet (or JApplet for Swing) and overrides the lifecycle methods init(), start(), stop(), and destroy(). The paint(Graphics g) method is called whenever the applet needs to be redrawn, and you request a redraw with repaint(). Applets can accept parameters from the hosting HTML via the <param> tag and getParameter(), can draw shapes and text using the Graphics class, and can handle mouse and keyboard events using the standard AWT delegation model. Although applets are largely obsolete in production, they remain a valuable pedagogical tool for understanding Java component architecture, the AWT graphics model, and event-driven programming.
Important Questions
- Differentiate between an applet and an application. Give at least five points of comparison.
- Describe the applet lifecycle with a diagram and explain when each method is called.
- Write an applet that displays "Welcome to BCA" in blue color at coordinates (50, 100).
- What is the role of the
Graphicsclass in applet programming? List at least six methods it provides. - Explain the security restrictions imposed on applets downloaded from the internet.
- Write an applet that uses a thread to animate a bouncing ball.
- Convert a simple applet into a standalone Swing application. Explain what changes are required.
- What is the difference between
paint()andrepaint()? - Write an applet that counts mouse clicks and displays the count.