Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks


How to Use TextAreas and TextFields

The TextArea(in the API reference documentation) and TextField(in the API reference documentation) classes display selectable text and, optionally, allow the user to edit the text. You can subclass TextArea and TextField, if necessary, to perform such tasks as checking for errors in the input. As with any Component, you can specify the background and foreground colors and font used by TextAreas and TextFields. You can't, however, change their basic appearance.

Both TextArea and TextField are subclasses of TextComponent.(in the API reference documentation) From TextComponent they inherit methods that allow them to set and get the current selection, enable and disable editing, get the currently selected text (or all the text), and set the text.

Below is an applet that displays first a TextField and then a TextArea. The TextField is editable; the TextArea isn't. When the user presses Return in the TextField, its contents are copied to the TextArea and then selected in the TextField.

Here's the program. Here's just its code that creates, initializes, and handles events in the TextArea and TextField:

//Where instance variables are defined:
TextField textField;
TextArea textArea;

public void init() {
    textField = new TextField(20);
    textArea = new TextArea(5, 20);
    textArea.setEditable(false);

    ...//Add the two components to the panel. 
}

public boolean handleEvent(Event evt) {
    if (evt.id == Event.ACTION_EVENT) {
        String text = textField.getText();
        textArea.appendText(text + "\n");
        textField.selectAll();
    }
    return super.handleEvent(evt);
}
[Should discuss further what you can do with TextField and TextArea. It'd be nice to have an example of subclassing TextField.] [Should show the constructors.]


Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks