A user opens a page containing an applet, minimises the browser, restores it, and finally closes the tab. List the life-cycle and painting calls in order.
An applet is a Java program embedded in a web page and driven by the browser through init(), start(), paint(), stop() and destroy(). Covers the Applet class and architecture, the life cycle, the applet tag and parameters, Graphics display methods, repaint()/update()/paint(), security and deprecation.
<applet code="X.class" width=… height=…> with <param name=… value=…> tags; read them with getParameter(name) — a String, or null. Also getDocumentBase(), getCodeBase(), showStatus().An applet is a small Java program that is downloaded along with a web page and runs inside it, in a rectangle reserved by the page. It was run by a browser equipped with the Java Plug-in, or by the JDK's appletviewer tool. When Java launched in 1995, applets — running in Sun's HotJava browser and then in Netscape Navigator 2.0 — gave the web interactive calculators, charts, animations and games long before modern JavaScript existed.
Three things make an applet different from an ordinary Java application. It has no main() method: the browser (the applet container) creates the object and calls its life-cycle methods. It is event-driven and graphical by nature — it is a Panel that draws itself. And because it is code from the internet running on your machine, it is subject to security restrictions.
| When | What happened |
|---|---|
| 1995 | HotJava and Netscape Navigator 2.0 run Java applets |
| 1997–98 | JApplet arrives with Swing (Java Foundation Classes) |
| 2015–2017 | Browsers drop NPAPI plug-ins (Chrome 45 in 2015, Firefox 52 in 2017), so applets stop working |
| Java 9 (2017) | Applet API and appletviewer deprecated (JEP 289) |
| Java 11 (2018) | appletviewer and the browser plug-in removed — the JDK can no longer run applets |
| Java 17 (2021) | Applet API deprecated for removal (JEP 398) |
| JDK 26 (2026) | The java.applet package and javax.swing.JApplet removed (JEP 504) |
Each level contributes something. As a Component, an applet can paint itself, set colours and fonts, and receive mouse and key events. As a Container it can hold Buttons, TextFields and other components. As a Panel its default layout is FlowLayout. The Applet class itself adds the life-cycle hooks and the methods for talking to the browser.
| Method | Purpose |
|---|---|
| init(), start(), stop(), destroy() | Life-cycle hooks called by the browser (empty by default — override what you need) |
| getParameter(String name) | The value of a <param> tag, as a String; null if it is absent |
| getDocumentBase() | URL of the HTML page that contains the applet |
| getCodeBase() | URL of the directory from which the applet's class was loaded |
| showStatus(String msg) | Show a message in the browser's or appletviewer's status bar |
| getImage(URL, name), getAudioClip(URL, name), play(URL, name) | Load images and sounds relative to a base URL |
| getAppletContext() | The browser environment: showDocument(url) opens a page; getApplet(name) finds another applet on the same page |
| getAppletInfo(), getParameterInfo() | Descriptions of the applet and of the parameters it accepts |
| isActive(), resize(w, h) | Whether the applet is started; request a new size |
The applet class must be public — the browser loads it from outside any package — and needs a public no-argument constructor (the default one is enough). Initialisation belongs in init(), not the constructor: while the constructor runs, the browser has not yet connected the applet to its page, so getParameter() and getCodeBase() cannot be used there.
An applet is event-driven: the browser owns the main loop and calls the applet's methods when something happens. Each call must return quickly — a method that loops or sleeps freezes the applet (and, in old browsers, the page). Long-running work such as an animation runs in a thread of its own, started in start() and stopped in stop(). Painting happens on the AWT event thread.
| Method | When the browser calls it | How often | Typical work |
|---|---|---|---|
| init() | After loading the class and creating the object | Once | Read parameters, set colours and fonts, create components, load images — the applet's 'constructor' |
| start() | Right after init(), and again whenever the page is revisited or the window restored | Many times | Start or resume animation threads and sounds |
| paint(Graphics g) | Whenever the applet's area must be drawn: first display, uncovered, resized, after repaint() | Many times | Draw text and shapes with g |
| stop() | When the user leaves the page or minimises the window — and always before destroy() | Many times | Pause threads and sounds so a hidden applet uses no CPU |
| destroy() | When the applet is removed from memory (the page or browser closes) | Once | Release resources: threads, connections |
Textbooks (Balagurusamy) describe the same cycle as states: Born (initialisation, entered through init()), Running (start()), Idle (stop() — and start() returns it to Running), Dead (destroy()), with the Display state entered whenever paint() draws the output.
import java.applet.Applet;
import java.awt.*;
/* <applet code="LifeCycle" width="320" height="120"></applet> */
public class LifeCycle extends Applet {
private String log = "";
public void init() { setBackground(Color.yellow); log += "init "; }
public void start() { log += "start "; }
public void stop() { log += "stop "; }
public void destroy() { System.out.println("destroy: releasing resources"); }
public void paint(Graphics g) {
log += "paint ";
g.drawString(log, 10, 40); // shows the order in which the browser called us
}
}<html>
<body>
<h3>KSHB scheme banner</h3>
<applet code="Banner.class" codebase="classes" width="400" height="80"
alt="Your browser understands applets but cannot run Java">
<param name="message" value="Applications open till 31 December">
<param name="speed" value="5">
Java is not available; this text is shown instead.
</applet>
</body>
</html>| Attribute | Meaning |
|---|---|
| code (required) | Name of the applet's class file, e.g. Banner.class |
| width, height (required) | Size of the applet's rectangle, in pixels |
| codebase | Directory (URL) holding the class files, if not the page's own directory |
| archive | JAR file(s) to download, e.g. archive="banner.jar" |
| name | A name other applets on the page can use with getApplet() |
| alt | Text for browsers that understand the tag but cannot run Java |
| align, hspace, vspace | Placement and spacing on the page |
Each <param name=… value=…> tag inside the applet tag passes one named value; ordinary text inside the tag is displayed by browsers that know nothing about applets. The applet tag was deprecated in HTML 4.01 in favour of <object> and is not part of HTML5.
import java.applet.Applet;
import java.awt.*;
public class Banner extends Applet {
private String msg;
private int speed;
public void init() {
msg = getParameter("message"); // a String, or null if missing
if (msg == null) msg = "Welcome to KSHB"; // always supply a default
String s = getParameter("speed");
speed = (s == null) ? 1 : Integer.parseInt(s); // numbers must be converted
setFont(new Font("SansSerif", Font.BOLD, 18));
}
public void start() {
showStatus("Loaded from " + getCodeBase()); // text in the status bar
}
public void paint(Graphics g) {
g.drawString(msg + " (speed " + speed + ")", 10, 40);
}
}appletviewer runs applets without a browser: appletviewer Banner.html opens a window for each applet tag in the file and ignores all other HTML. A popular shortcut puts the applet tag inside a comment at the top of the .java file (as in LifeCycle above) and runs appletviewer LifeCycle.java. The tool was removed in JDK 11.
If the page is http://www.example.org/schemes/index.html and its tag says codebase="classes", then getDocumentBase() returns http://www.example.org/schemes/index.html (the page) while getCodeBase() returns http://www.example.org/schemes/classes/ (where the class came from). Resources shipped with the applet are therefore loaded with getImage(getCodeBase(), "logo.gif").
paint() receives a java.awt.Graphics object — a drawing context for the applet's rectangle. The coordinate origin (0, 0) is the top-left corner; x grows to the right and y grows downwards; units are pixels.
| Method | What it draws |
|---|---|
| drawString(String s, int x, int y) | Text whose baseline starts at (x, y) — the letters sit above y |
| drawLine(x1, y1, x2, y2) | A straight line between two points |
| drawRect(x, y, w, h) / fillRect(…) | A rectangle outline / a filled rectangle, top-left corner at (x, y) |
| drawRoundRect(x, y, w, h, arcW, arcH) | A rectangle with rounded corners |
| clearRect(x, y, w, h) | Fill an area with the background colour |
| drawOval(x, y, w, h) / fillOval(…) | The ellipse inside that bounding box — a circle when w == h |
| drawArc(x, y, w, h, startAngle, arcAngle) / fillArc(…) | Part of an ellipse; degrees, 0 at 3 o'clock, positive anticlockwise |
| drawPolygon(int[] xs, int[] ys, int n) / fillPolygon(…) | A closed polygon through n points |
| drawImage(img, x, y, observer) | An Image (e.g. from getImage()) |
| setColor(Color c) / getColor() | The colour for later drawing: Color.RED, new Color(r, g, b) |
| setFont(Font f) / getFont() | new Font("Serif", Font.BOLD, 20); styles PLAIN, BOLD, ITALIC |
import java.applet.Applet;
import java.awt.*;
/* <applet code="House" width="300" height="220"></applet> */
public class House extends Applet {
public void init() {
setBackground(Color.white); // set once, not inside paint()
}
public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawRect(60, 100, 160, 100); // walls: x 60..220, y 100..200
int[] xs = {50, 140, 230};
int[] ys = {100, 30, 100};
g.setColor(Color.red);
g.fillPolygon(xs, ys, 3); // roof: a filled triangle
g.setColor(Color.darkGray);
g.fillRect(125, 150, 30, 50); // door: y 150..200, on the floor line
g.setColor(Color.orange);
g.fillOval(240, 20, 40, 40); // sun: a circle of diameter 40
g.setColor(Color.black);
g.setFont(new Font("Serif", Font.BOLD, 16));
g.drawString("KSHB Flat No. 7", 80, 218); // baseline at y = 218
}
}Colours come from constants such as Color.red or Color.RED (both spellings exist since Java 1.4) or from new Color(r, g, b) with components 0–255. setBackground() and setForeground() are Component methods that set the applet's own colours, while g.setColor() affects only what that Graphics object draws next.
AWT paints for two reasons. System-triggered painting happens when the applet is first shown, uncovered after being hidden, or resized — the AWT then calls paint(g) directly. Application-triggered painting happens when the program has changed its own state (a counter, a position) and wants the screen to show it — the program calls repaint().
repaint() has variants: repaint(long ms) (within ms milliseconds) and repaint(x, y, w, h) (only a region).Flicker. In an animation the default update() erases the whole area to the background colour and then paint() draws the new frame, so for an instant the screen is blank — dozens of times a second, which the eye sees as flashing. The cure has two parts that work together: override update() so that it calls paint() without clearing, and use double buffering — draw each complete frame into an off-screen Image (createImage(w, h), then getGraphics()) and copy it to the screen with a single drawImage(). (Double buffering alone does not help while the default update() keeps clearing the screen.) Swing components are double-buffered automatically, and Swing code overrides paintComponent() instead.
import java.applet.Applet;
import java.awt.*;
/* <applet code="Ball" width="300" height="100"></applet> */
public class Ball extends Applet implements Runnable {
private int x = 0;
private volatile Thread animator; // set to null in stop() to end the loop
private Image buffer; // off-screen image for double buffering
private Graphics bg;
public void start() { // page shown: start the animation
animator = new Thread(this);
animator.start();
}
public void stop() { // page hidden: let the thread finish
animator = null;
}
public void run() {
Thread me = Thread.currentThread();
while (animator == me) {
x = (x + 5) % getWidth();
repaint(); // request update() -> paint()
try { Thread.sleep(40); } catch (InterruptedException e) { return; }
}
}
public void update(Graphics g) { // skip the default clearing: no flicker
paint(g);
}
public void paint(Graphics g) {
if (buffer == null) {
buffer = createImage(getWidth(), getHeight());
bg = buffer.getGraphics();
}
bg.setColor(getBackground());
bg.fillRect(0, 0, getWidth(), getHeight()); // clear the OFF-SCREEN image
bg.setColor(Color.red);
bg.fillOval(x, 30, 40, 40);
g.drawImage(buffer, 0, 0, this); // one copy to the screen
}
}| Point | Applet | Application |
|---|---|---|
| Entry point | No main(); the browser calls init(), start() … | public static void main(String[] args) |
| Runs in | A browser's Java Plug-in or appletviewer | A JVM started with the java command |
| Class requirement | A public class extending Applet (or JApplet) | Any class with a main method |
| User interface | Always graphical — it is a Panel | Console or GUI |
| Output | Graphics methods such as drawString() | System.out, files, windows |
| Security | Untrusted applets run in a sandbox | Full access, with the user's own rights |
| Life cycle | Controlled by the browser | Controlled by the program; ends when main and all user threads finish |
| Delivery | Downloaded automatically with a web page | Installed and launched by the user |
JApplet (javax.swing) is the Swing version of Applet: components go into its content pane, it supports Swing menus, and painting is double-buffered. It was deprecated and removed together with the rest of the Applet API. Rich web content moved to JavaScript, HTML5 canvas and WebAssembly; Java desktop programs are now distributed as stand-alone applications (for example packaged with jpackage), often built with Swing or JavaFX.
Try the problem first, then reveal the working one step at a time.
A user opens a page containing an applet, minimises the browser, restores it, and finally closes the tab. List the life-cycle and painting calls in order.
In the House applet (300 × 220), describe exactly where the walls, roof, door, sun and caption appear.
The Banner applet reads message and speed. What appears for: (a) the page shown in Section 4; (b) a page with no message param but speed = 5; (c) a page with speed = "fast"?
Follow one frame of the Ball applet from run() to the screen, and explain what would go wrong if (a) update() were not overridden, (b) paint() drew straight onto g without the buffer and without clearing.
Which applet life-cycle methods are called exactly once and which may be called many times? In which class is each of init(), start(), stop(), destroy() and paint() defined?
Write the applet tag for a class Clock (packed in clock.jar) that occupies 200 × 200 pixels and receives a parameter zone with the value IST. How does the applet read the parameter?
Explain why an AWT animation applet flickers, give two remedies, and say how Swing avoids the problem.
For the LifeCycle applet of Section 3, what text is on screen (a) after the page first loads, and (b) after the user minimises and then restores the window? Assume paint() runs once per exposure.
An unsigned applet loaded from www.example.org tries each of the following. Which are allowed? (a) drawing an image fetched with getImage(getCodeBase(), "logo.gif"); (b) opening a Socket to www.example.org; (c) opening a Socket to www.bank.example; (d) reading C:\data\marks.txt; (e) calling System.exit(0); (f) showing a message with showStatus().
<param> tags — convert numbers yourself; applets do not receive command-line arguments.12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.