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 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.
Here is an outline of the Voyage.java program that creates the Voyage applet:
// FILE: BagApplet.java | |||||||||||
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 |
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.
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 AppletThe 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.
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.", 8, 60, TextArea.SCROLLBARS_NONE );
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.
launch
, and the label on the button is the string "
LAUNCH!
":
Button launch = new Button("LAUNCH!");
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.
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.
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:
We can add one of the interactive components to the GUI. This is done with an applet method called add. The method has one argument, which is the component that is being added to the GUI. For example, one of our buttons is sizeButton , so we can write the statement:
add(launch);As components are added, the GUI fills up from left to right. If there is no room for a component on the current line, then the GUI moves down and starts a new row of components. Later you can learn more sophisticated ways of laying out the components of a GUI, but the simple left-to-right method used by an applet is a good starting point.
We can display messages in the GUI. Each message is a fixed string that provides some information to the user. Each of these messages is a Label object (from the package java.awt ). To create and display a message, we activate add, with a newly created Label as the argument. For example:
add(new Label("Distance of trip in light years"));The Label constructor has one argument, which is the string that you want to display. The add method will put the message in the next available spot of the GUI.
If our applet class has other methods (besides init), then we can activate these other methods. For example, we plan to have two other methods in the IntArrayBag class:
void addNewLine( ); void addHorizontalLine(Color c);The addNewLine method forces the GUI to start a new line, even if there's room for more components on the current line. The second method, addHorizontalLine , draws a horizontal line in the specified color. We'll have to define these two methods as part of BagApplet.Java , but they won't be difficult. (The data type Color is part of java.lang . It includes Color.blue and twelve other colors plus the ability to define your own colors.)
The buttons and other components have methods that can be activated. For example, one of the methods of a TextField is called append . The method has one argument, which is a string, and this string is appended to the end of what's already in the text field. One of the statements in our init method will activate append in this way:
feedback.append("Bon Voyage!\n");This causes the message "Bon Voyage!" to be written in the feedback text field (with a newline character \n at the end of the message).
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.
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. |
addNewLine()
| These are not actually Applet methods--you'll need to define them if you want to use them. |
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)
|
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. |
t.requestFocus()
| 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 components width and height are set to the given values in pixels. |
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( ); return; } acceleration = atod(accelerationText.getText( )); if (acceleration == Double.NaN || acceleration <= 0) { answers.setText("Type a positive acceleration before launching."); accelerationText.requestFocus( ); accelerationText.selectAll( ); return; } 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 LaunchListener.java. 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:
// Tell the button what it should do when clicked: launch.addActionListener(new LaunchListener( ));
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); line.setBackground(c); add(line); }
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 BagApplet.java 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.
An applet can be compiled just like any other Java program. For example, using the Java Development Kit we can compile BagApplet.java with the command line:
javac Voyage.java
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> </applet>
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:
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 .
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.