Previous | Next | Trail Map | Writing Applets | Overview of Applets


Methods for Adding UI Components

The Simple applet's display code (implemented in its paint() method) is flawed: It doesn't support scrolling. Once the text it displays reaches the end of the display rectangle, you can't see any new text. Here's an example of the problem:

The simplest cure for this problem is to use a pre-made user interface (UI) component that has the right behavior.

Note: This page glosses over many details. To really learn about using UI components, go to Creating a User Interface .

Pre-Made UI Components

The AWT supplies the following UI components (the class that implements each component is listed in parentheses):

Methods for Using UI Components in Applets

Because the Applet class inherits from the AWT Container class, it's easy to add components to applets and to use layout managers to control the components' onscreen positions. Here are some of the Container methods an applet can use:
add()
Adds the specified Component.
remove()
Removes the specified Component.
setLayout()
Sets the layout manager.

Adding a Non-Editable Text Field to the Simple Applet

To make the Simple applet use a scrolling, non-editable text field, we can use the TextField class. Here is the revised source code. The significant changes are shown below.
. . .

//Instead of creating a StringBuffer, create a TextField:
java.awt.TextField field = new java.awt.TextField(80);

public void init() {
    //Add the TextField, and then display it.
    field.setEditable(false);
    setLayout(new java.awt.GridLayout(1,0));
    add(field);
    validate();
    addItem("initializing... ");
}

. . .

public void addItem(String newWord) {
    //This used to append the string to the StringBuffer;
    //now it appends it to the TextField.
    String t = field.getText();
    System.out.println(newWord);
    field.setText(t + newWord);
    repaint();
}

//The paint() method is no longer necessary,
//since the TextField repaints itself automatically.
Below is the resulting applet.


You can't run applets. Here's what you'd see if you could:



Previous | Next | Trail Map | Writing Applets | Overview of Applets