The JavaTM Tutorial

| Start of Tutorial > Start of Trail | Search Feedback Form

Trail: Getting Started

## Lesson: The Anatomy of an 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. Importing Classes and Packages gives you more information about packages and the `import` statement.

### 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). Defining an `Applet` Subclass tells you how.

### 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. Implementing `Applet` Methods talks about the `paint` method, how the "Hello World" applet implements it, and the other methods applets commonly implement.

### 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. Running an Applet gives more details.

| Start of Tutorial > Start of Trail | Search Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.