Previous | Next | Trail Map | Writing Applets | The Anatomy of an Applet


Methods for Adding UI Components

public class Simple extends java.applet.Applet {
    . . . 
    public void paint(Graphics g) {
	g.clearRect(0, 0, size().width - 1, size().height - 1);
	g.drawRect(0, 0, size().width - 1, size().height - 1);
	g.drawString(buffer.toString(), 5, 15);
    }
}
The Simple applet has a display problem: It doesn't scroll. Once the text it displays reaches the end of the display area, you can't see any new text. The simplest cure for this problem is to use a pre-made 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 Component subclass for each 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. Each Applet has a layout manager that determines how the Components are placed within the display area. Here are some of the methods the Container class supplies, which you can use to include and position Components in your applet:
add()
Adds the specified Component to this Container.
remove()
Removes the specified Component from this Container.
getComponents()
Gets all the Components in this Container.
locate()
Locates the Component at the specified x,y position.
setLayout()
Sets the layout manager for this Container.
preferredSize()
Returns the preferred size of this Container.

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 main changes are listed below.
TextField field = new TextField(80);
//We used to use a StringBuffer.

public void init() {
    //Add the TextField, and then display it.
    field.setEditable(false);
    add(field);
    resize(field.preferredSize());
    show();
    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.


Your browser doesn't understand the APPLET tag, and there's no Alpha version of this applet. The reason: With the Alpha 3 and earlier APIs, it's difficult to write an applet that uses the AWT.

Where Can I Find More Information?

Using Components is covered in detail in Creating a User Interface . For more information on the methods listed above, you can also refer to the Container API reference page.


Previous | Next | Trail Map | Writing Applets | The Anatomy of an Applet