How to Write a Simple Applet

A Java applet is a Java program written in a special format to have a graphical user interface. The graphical user interface is also called a GUI (pronounced "gooey"), and it allows a user to interact with a program by clicking the mouse, typing information into boxes, and performing other familiar actions. With a Java applet, GUIs are easy to create even if you've never run into such goo before.

This section shows a pattern for developing such applets. To illustrate the pattern, we'll implement an applet that lets you determine the time required for a long voyage. When the voyage applet starts, a GUI is created, as shown here:

By the way, the word "applet" means a particular kind of Java program, so you might show the drawing to your boss and say "My applet created this nice GUI." But you can also use the word "applet" to talk about the GUI itself, such as "The applet in this drawing has two text entry boxes and a button.

The Voyage Applet

The Voyage applet in the above drawing is intended to show some of the simplest GUI components. When the applet starts, two text entry boxes appear at the top with the labels "Distance of trip in light years" and "Acceleration of rocket in g's". In the middle of the applet is a button labeled "Launch!", and at the bottom of the applet is a text area for the applet to write messages to the user.

You can try interacting with the applet a little bit by typing some numbers into the box and then clicking the Launch button.

The Parts of a Simple Interactive Java Applet

Here is an outline of the program that creates the Voyage applet:

// FILE:

1. Import statements. These statements provide the items that all applets use:

   import java.applet.Applet; // Provides the Applet class.
   import java.awt.*;         // Provides Button class, etc.
   import java.awt.event.*;   // Provides ActionEvent, ActionListener 

2. The Class Definition. The important parts of the Voyage class definition are shown here:

   public class BagApplet extends Applet
2a. Declarations of the applet's components. These will be the declarations of buttons, text areas, and other GUI components that appear in the applet.
2b. The init method.
public void init( )
2c. Implementations of the action listeners. This code tells the applet what to do when each of the buttons is pressed.
2d. Implementations of other methods. These are methods that are activated from within init to carry out various subtasks.

The Import Statements

As with any Java program, we begin with a collection of import statements to tell the compiler about the other classes that we'll be using. In the case of the Voyage applet, we have these three import statements:

   import java.applet.Applet;
   import java.awt.*;
   import java.awt.event.*;
The first import statement provides a class called Applet, which we'll use in a moment. The other two import statements provide items from the abstract windowing toolkit (the "AWT"), which is a collection of classes for drawing buttons and other GUI items.

The Class Definition

After the import statements, we define a class, much like any other Java class. This class definition begins with the line:

   public class Voyage Applet extends Applet
The class definition continues down to the last closing bracket of the file. The class is called Voyage, which is certainly a good name, but what does "extends Applet" mean? It means that the Voyage class will not be written entirely by us. Instead, the class begins by already having many methods of another class called Applet. We imported the Applet class from java.applet.Applet, and it is provided as part of the Java language so that a class such as Voyage does not have to start from scratch. The act of obtaining methods from another class is called inheritance. The class that provides these methods (such as the Applet class) is called the base class, and the new class (such as our Voyage class) is called the extended class.

Declaration of the Applet's Components

An applet's components are the buttons and other items that are displayed when the applet runs. These components are declared as instance variables of the class. Our bag applet has several kinds of components: a button, text fields (which are the white rectangles), and a text area (which is the large rectangle at the bottom part of the applet). In all, there are four important components in the Voyage applet, represented by these four instance variables:

   TextField distanceText = new TextField(10);
   TextField accelerationText = new TextField(10);
   Button launch = new Button("LAUNCH!");
   TextArea answers = new TextArea(
       "I am ready for your first trip.",

All the instance variables are declared near the top of the class definition, before any of the method definitions. They cannot have the usual private keyword because they'll be accessed from other classes that we'll see shortly. But before that, let's look at the three kinds of components: button, text field, and text area.

A button is a grey rectangle with a label. When a button is created, the constructor is given a string that is printed in the middle of the button. For example, this declaration creates a button called launch, and the label on the button is the string " LAUNCH!":
   Button launch = new Button("LAUNCH!");

Text Field
A text field is a white rectangle that can display one line of text. A text field is set up so that the program's user can click on the field and type information, and the applet can then read that information. Our applet has two text fields. The TextField class has a constructor with one argument--an integer that specifies approximately how many characters can fit in the text field. For example, one of our text fields is declared as:

   TextField distanceText = new TextField(10);
The elementText text field can hold about 10 characters. The user can actually type beyond 10 characters, but only 10 characters of a long string will be displayed.

Text Area
A text area is like a text field with more than one line. Its constructor has four arguments are documented in the comments here:
   TextArea answers = new TextArea(
       "I am ready for your first trip.", // Initial text
       8,                                 // Number of rows
       60,                                // Number of columns
       TextArea.SCROLLBARS_NONE           // Do not include scroll bars
This large text area appears at the bottom of the applet. The intention is to use the text area to display messages to the user.

The declarations we have seen created the three kinds of components: Button, TextField, TextArea. All three classes are part of the java.awt package that is imported by our applet. When we declare a button (or other component) and create it with the constructor, it does not immediately appear in the GUI. How do the objects get placed in the GUI? Also, how does the applet know what to do when the user clicks on a button or takes some other action? The answers to these two questions lie in a special applet method called init, which we'll discuss next.

The init Method

A Java application program has a special static method called main. A Java applet does not have main. Instead, an applet has a special nonstatic method called init. When an applet runs, the runtime system creates an object of the applet class, and activates init( ) for that object. There are several other applet methods that the runtime system also activates at various times, but an interactive test program needs only init.

Our init method carries out four kinds of actions:

Action Listeners

The most important method for buttons involves a new kind of object called an action listener. An action listener is object that an applet programmer creates to describe the action that should be taken when certain events occur. Our Voyage applet will have one kind of action listener called LaunchListener. A LaunchListener is actually a new class that we'll define in a moment. i But the only thing you need to know for the init method is how to connect an action listener to a Button . The solution is to activate a method called addActionListener for each Button . For example, to connect the launch button to its action listener, we place this statement in the init method: launch.addActionListener(new LaunchListener( )); Notice that addActionListener is a method of the Button class, and its one argument is a new LaunchListener object. Of course, we still need to implement the LaunchListener class. We'll look at how this is done in a moment, after we summarize what we've seen so far.

What Can Appear in the Init Method

Methods to Call from an Applet or from a Class That Extends an Applet
add(component) The component may be any of Java's AWT components such as Button, TextArea, or TextField. As components are added, the applet fills up from left to right. If there is no room for a component on the current line, then the applet moves down and starts a new row of components.
addHorizontalLine(Color c)
These are not actually Applet methods--you'll need to define them if you want to use them.

Three Kinds of GUI Components

Constructors for Three Useful Applet Components
Button(String label) Creates a button with a given label.
TextField(int size) Creates a white box for the user to type information. The size is the number of characters.
TextArea(int rows, int columns) Creates a box with the given number of rows and columns--often for displaying information to the user.

Important Methods That a GUI Object Can Activate

Six Useful Methods for a Component
b.setActionListener (ActionListener act) We use b.setActionListener for a Button b. The ActionListener, act, describes the actions to take when the Button b is pressed.
t.append(String message) We use t.append for a TextArea t. The specified message is added to the end of the TextArea.
t.getText() We use t.getText for a TextField t. The method returns a copy of the String that the user has typed in the field.
t.setEditable (boolean editable) The component t can be a TextArea or a TextField. The boolean parameter tells whether you want the user to be able to type text into the component.
We use these methods with a TextField. The requestFocus method causes the mouse to go to the field, and selectAll causes all text to be highlighted.
c.setSize (int width, int height) This method may be used with any component c. The component¬ís width and height are set to the given values in pixels.

Implementation of the LaunchListener

The next step of the applet implementation is to design and implement an action listener class for our launch button. The purpose of an action listener is to describe the action that is carried out when a button is pushed.

Here's the Java syntax for defining an action listener class--the blank line is filled in with your choice of a name for the action listener class.

   class _______________ implements ActionListener
      void actionPerformed(ActionEvent event)
The phrase " implements ActionListener " informs the Java compiler that the class will have a certain method that is specified in the ActionListener interface that is part of java.awt.* . The method, called actionPerformed , is shown with "..." to indicate where its body should be written. The actionPerformed method will be executed when an action occurs in the action listener's component, such as clicking a button. For example, here is the complete definition of the action listener that handles the clicking of the launch button of our Voyage applet:
      public void actionPerformed(ActionEvent event)
         double distance;     // Distance of the trip in light years.
         double acceleration; // Acceleration of the trip in g's.
         distance = atod(distanceText.getText( ));
         if (Double.isNaN(distance) || distance < 0)
            answers.setText("Type a non-negative distance before launching.");
            distanceText.requestFocus( );
            distanceText.selectAll( );
         acceleration = atod(accelerationText.getText( ));
         if (acceleration == Double.NaN || acceleration <= 0)
            answers.setText("Type a positive acceleration before launching.");
            accelerationText.requestFocus( );
            accelerationText.selectAll( );
         makeTrip(distance, acceleration);
This declares a class called LaunchListener, which includes its own actionPerformed method. For most classes, the class definition would go in a separate file called But a separate file is undesirable here because the actionPerformed method needs access to instance variables such as the two text fields. The necessary access can be provided by placing the entire LaunchListener definition within the Voyage class. This is an example of an inner class, where the definition of one class is placed inside of another. An inner class has two key properties:

So, by making LaunchListener an inner class, the actionPerformed method can activate methods such as answers.setText. By the way, the actionPerformed method has a parameter called event . For more complex actions, the event can provide more information about exactly which kind of action triggered the actionPerformed method. Once an action listener is created, it must be registered with its particular button. The registration is made in the init method. Our applet had this statement to register the LaunchListener object:
      // Tell the button what it should do when clicked:
      launch.addActionListener(new LaunchListener( ));

Implementations of Other Methods

Our applet has two other methods that we've mentioned: (1) addHorizontalLine , which draws a horizontal line in a specified color; and (2) addNewLine , which causes a new line to start in the GUI, even if there's room for more components on the current line. Our addHorizontalLine doesn't really draw a line. Instead, it adds a component called a Canvas to the applet. A Canvas is another applet component, like a Button , primarily used for drawing graphical images. The size of the Canvas can be set in pixels, which are the individual dots on a computer screen. Today's typical screens have about 100 pixels per inch, so a Canvas that is only one pixel high looks like a horizontal line. Here's our implementation:

   private void addHorizontalLine(Color c)
      // Add a Canvas 10000 pixels wide but 
      // only 1 pixel high, which acts as
      // a horizontal line.
      Canvas line = new Canvas( );
      line.setSize(10000, 1);

Notice that the Canvas is 10,000 pixels wide, which is wide enough to span even the largest applet--at least on today's computer screens.

Our last method, addNewLine , works by calling addHorizontalLine with the color set to the background color of the applet. In effect, we are drawing a horizontal line, but it is invisible since it's the same color as the applet's background.

The implementation of addNewLine is given in as part of the complete applet. Look through the whole applet with an eye toward how it can be expanded to test all of the bag's methods or to test a different class.

How to Compile and Run an Applet

An applet can be compiled just like any other Java program. For example, using the Java Development Kit we can compile with the command line:


You may have some other way of compiling Java programs in your development environment, but the result will be the same. The act of compiling produces the file Voyage.class. The compilation will probably produce other files with names such as Voyage$LaunchListener.class . This is the compiled version of the inner class.

Applets were actually created to run as part of a page that you view over the Internet with a web browser. These pages are called html pages, which stands for "hyper-text markup language." So, to run the Voyage applet, we need a small html file. The file, called Voyage.html, should be created by you in the same directory as Voyage.class, and it should contain the two lines of html code shown here:

   <applet code="Voyage.class" width=480 height=340>

The first line, containing <applet...> tells the web browser that you are going to start an applet. Usually, you will have at least three pieces of information about the applet:

code = "Voyage.class"
Tells the browser where to find the compiled class.

width = 480
Tells the width of the applet in pixels.

height = 340
Tells the height of the applet in pixels.

Many Java development environments have a feature to automatically create a small html file such as this.

Once the html file is in place, you can run the applet in one of two ways. One approach is to run an appletviewer, which is a tool that reads an html file and runs any applets that it finds. The Java Development Kit has an appletviewer that is executed from the command line. For example, to run the JDK appletviewer you change to the directory that contains Voyage.html and type the command:

        appletviewer BagApplet.html

This command runs the applet. The applet can also be displayed by putting the class and html files in a location that's available to your web browser .

Beyond the init Method

Our test applet needed to define only the init method. More complex applets can also be created, involving graphical images plus interaction. Graphical applets will generally provide other methods called start , paint , update , stop , and destroy . A good resource is Graphic Java Mastering the AWT by David M. Geary.