Previous | Next | Trail Map | Getting Started | The "Hello World" Applet


The Anatomy of a Java Applet

Now that you've seen a Java applet, you're probably wondering how it works. Remember that a Java applet is a program that adheres to a set of conventions that allows it to run within a Java-compatible browser.

Here again is the code for the "Hello World" applet.

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {
    public void paint(Graphics g) {
        g.drawString("Hello world!", 50, 25);
    }
}

Importing Classes and Packages

The code above starts off with two import statements. By importing classes or packages, a class can more easily refer to classes in other packages. In the Java language, packages are used to group classes, similar to the way libraries are used to group C functions.

Defining an Applet Subclass

Every applet must define a subclass of the Applet class. In the "Hello World" applet, this subclass is called HelloWorld. Applets inherit a great deal of functionality from the Applet class, ranging from communication with the browser to the ability to present a graphical user interface (GUI).

Implementing Applet Methods

The HelloWorld applet implements just one method, the paint() method. Every applet must implement at least one of the following methods: init(), start(), or paint(). Unlike Java applications, applets do not need to implement a main() method.

Running an Applet

Applets are meant to be included in HTML pages. Using the <APPLET> tag, you specify (at a minimum) the location of the Applet subclass and the dimensions of the applet's onscreen display area. When a Java-capable browser encounters an <APPLET> tag, it reserves onscreen space for the applet, loads the Applet subclass onto the computer the browser is executing on, and creates an instance of the Applet subclass. Next, the browser calls the applet's init() and start() methods, and the applet is off and running.


Previous | Next | Trail Map | Getting Started | The "Hello World" Applet