Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages

How to Use Text Fields

Text fields display a single line of selectable, optionally editable text. Generally you use the JTextField(in the API reference documentation) class to provide text fields. If you need to provide a password field -- an editable text field that doesn't show the characters the user types -- use the JPasswordField class instead. This section discusses both text fields and password fields.

If you want a text field that also provides a menu of strings to choose from, consider using an editable combo box. If you need to obtain more than one line of input from the user, then you should use one of the classes that implements a general-purpose text area.

The applet pictured below is the Swing version of an AWT example program described in How to Use TextAreas and TextFields(in the Creating a User Interface trail).

[PENDING: in the figure put a callout to the field and the area]

The applet displays a basic text field and a text area. The text field is editable; the text area isn't. When the user presses Return in the text field, the field fires an action event(in the Creating a User Interface trail). The applet reacts to the event by copying the text field's contents to the text area, and then selecting all the text in the text field.

You can find the source for the program in TextDemo.java. The corresponding HTML file, TextDemo.html, contains an <APPLET> tag for running the applet. [PENDING: should use OBJECT/EMBED tags, too, so this will work with Plug-in.] Here's the code from TextDemo that creates the text field in the applet:

textField = new JTextField(20);
...
getContentPane().add(textField);
...
textField.addActionListener(this);
The JTextField constructor takes an integer parameter indicating the desired number of columns in the text field. The next lines of code add the text field to the applet's content pane, and then register the applet as an action listener for the text field. Here's the actionPerformed method that handles action events from the text field:
public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}
This example illustrates using a basic, off-the-shelf text field for entering textual data and performing some task when the text field fires an action event. This is sufficient for many programs. Other programs, however, need more advanced behavior. As a subclass of JTextComponent(in the API reference documentation), JTextField can be configured and customized. One common customization is to provide a text field whose contents are validated. This topic and others are covered in the sections that follow:

Creating a Validated Field

Many programs require users to enter textual data of a certain type or format. For example, a program might provide a text field for entering a date, a decimal number, or a phone number. The contents of such a text field must be validated before being used for any purpose. A text field can be action-validated or keystroke-validated.

The data in an action-validated field is checked each time the field fires an action event (each time the user presses the return key). An action-validated field might, at any given point in time, contain invalid data. However, the data is validated before it's used for anything. To create an action-validated field, provide an action listener for your field and implement its actionPerformed method as follows:

The data in a keystroke-validated field is checked each time the field changes. A field that is keystroke-validated can never contain invalid data because every keystroke that causes the data to be invalid is rejected. To create a keystroke-validated text field you need to provide a custom document for your text field. If you aren't familiar with documents yet, see Working With a Text Component's Document.

Warning: Do not use a document listener for keystroke validation. By the time a document listener has been notified of a change, it's too late, the change has already taken place. See the last couple of paragraphs in Listening for Changes on a Document for more information.
The application shown in the following figure has four keystroke-validated text fields. The user enters loan information into the first three text fields. Each time the user types a character, the program validates the input and updates the result in the fourth text field.
[PENDING: retake this snapshot with the smaller loan amount.]

Try this:
  1. Compile and run the application. The source file is TextFieldDemo.java. You will also need WholeNumberField.java, DecimalField.java, and FormattedDocument.java.
    See Getting Started with Swing if you need help.
  2. Enter information into the text fields and see the results.
    If attempt to you enter invalid data, the program beeps.
  3. Try to type into the fourth text field.
    You can't because it isn't editable. However, you can select the text.
  4. Resize the window.
    Note how the labels and text fields remain aligned. Laying Out Label/Text Field Pairs talks more about this feature of the program.

The Years field is an instance of WholeNumberField.java, which is a subclass of JTextField. By overriding the createDefaultModel method, WholeNumberField establishes a custom Document subclass -- an instance of WholeNumberDocument -- as the document for each WholeNumberField created:
protected Document createDefaultModel() {
    return new WholeNumberDocument();
}
Here's the implementation of WholeNumberDocument:
protected class WholeNumberDocument extends PlainDocument {

    public void insertString(int offs, String str, AttributeSet a)
                    throws BadLocationException {

        char[] source = str.toCharArray();
        char[] result = new char[source.length];
        int j = 0;

        for (int i = 0; i < result.length; i++) {
	    if (Character.isDigit(source[i]))
	        result[j++] = source[i];
	    else {
	        toolkit.beep();
	        System.err.println("insertString: " + source[i]);
	    }
        }    
        super.insertString(offs, new String(result, 0, j), a);
    }
}
This class overrides the insertString method which is called every time any string or character is about to be inserted into the document. WholeNumberDocument's implementation of insertString evaluates each character to be inserted into the text field. If the character is a digit, the document allows it to be inserted. Otherwise, the method beeps and prints an error message. Thus WholeNumberDocument allows the numbers in the range 0, 1, 2, ...

An interesting implementation detail is that our custom document class does not have to override the remove method. The remove method is called each time a character or group of characters is removed from the text field. Because removing a digit from an integer cannot produce an invalid result, this class does not pay attention to removals.

The other two input fields in the example, as well as the uneditable Monthly Payment field, are all instances of DecimalField.java, a custom JTextField subclass. DecimalField uses a custom document, FormattedDocument, that allows only data of a particular format to be entered.

FormattedDocument has no knowledge of the actual format of its content. Instead, FormattedDocument relies on a format, an instance of a subclass of Format(in the API reference documentation), to accept or reject a proposed change. The text field that uses the FormattedDocument must specify which format the FormattedDocument uses.

The Loan Amount and Monthly Payment text fields use a NumberFormat(in the API reference documentation) object created like this:

moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);
((DecimalFormat)moneyFormat).setPositiveSuffix(" ");
The following code creates the APR text field's format:
percentFormat = NumberFormat.getPercentInstance(Locale.US);
percentFormat.setMinimumFractionDigits(3);
As the code shows, the same class (NumberFormat) can support a currency format and a percentage format. Furthermore, Format and its subclasses are locale-sensitive, so decimal field can be made to support formats for other countries and regions. Refer to Formatting(in the Internationalization trail) in the internationalization trail for detailed information about formats.

Here is FormattedDocument's implementation of insertString:

public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

    String currentText = getText(0, getLength());
    String beforeOffset = currentText.substring(0, offs);
    String afterOffset = currentText.substring(offs, currentText.length());
    String proposedResult = beforeOffset + str + afterOffset;

    try {
        format.parseObject(proposedResult);
        super.insertString(offs, str, a);
    } catch (ParseException e) {
        Toolkit.getDefaultToolkit().beep();
        System.err.println("insertString: could not parse: " + proposedResult);
    }
}    
The method uses the format to parse the result of the proposed insertion. If the result is properly formatted, this method calls its superclass's insert method to do the insertion. If the result is not properly formatted, the computer beeps.

In addition to overriding insertString, FormattedDocument also overrides the remove method. Recall that the remove method is called each time a character or group of characters is to be removed from the document.

public void remove(int offs, int len) throws BadLocationException {
    String currentText = getText(0, getLength());
    String beforeOffset = currentText.substring(0, offs);
    String afterOffset = currentText.substring(len + offs, currentText.length());
    String proposedResult = beforeOffset + afterOffset;

    try {
        if (proposedResult.length() != 0)
            format.parseObject(proposedResult);
        super.remove(offs, len);
    } catch (ParseException e) {
        Toolkit.getDefaultToolkit().beep();
        System.err.println("remove: could not parse: " + proposedResult);
    }
}    
The FormattedDocument implementation of the remove method is similar to its implementation of the insertString method. The format parses the result of the proposed change and performs the removal or not, depending on whether the result is valid.

Using a Document Listener on a Text Field

So, if you can't use a document listener for field validation, what can you use it for? Use it to listen to, but not interfere with, changes to the document's content. The loan calculator uses the following document listener to update the monthly payment after every change:
class MyDocumentListener implements DocumentListener {
    public void insertUpdate(DocumentEvent e) {
        update(e);
    }
    public void removeUpdate(DocumentEvent e) {
        update(e);
    }
    public void changedUpdate(DocumentEvent e) {
        // we won't ever get this with a PlainDocument
    }
    private void update(DocumentEvent e) {
        Document whatsup = e.getDocument();
        if (whatsup.getProperty("name").equals("amount"))
            amount = amountField.getValue();
        else if (whatsup.getProperty("name").equals("rate"))
            rate = rateField.getValue();
        else if (whatsup.getProperty("name").equals("numPeriods"))
            numPeriods = numPeriodsField.getValue();
        payment = computePayment(amount, rate, numPeriods);
        paymentField.setValue(payment);
    }
}    
This is an appropriate use of a document listener.

For general information about document listeners refer to How to Write a Document Listener.

Laying Out Label/Text Field Pairs

Rows of label and text field pairs such as those found in the loan calculator are quite common on preference panels and panels that implement forms. Here's the code that lays out the label and text field pairs.
. . .
//Layout the labels in a panel
JPanel labelPane = new JPanel();
labelPane.setLayout(new GridLayout(0, 1));
labelPane.add(amountLabel);
labelPane.add(rateLabel);
labelPane.add(numPeriodsLabel);
labelPane.add(paymentLabel);

//Layout the text fields in a panel
JPanel fieldPane = new JPanel();
fieldPane.setLayout(new GridLayout(0, 1));
fieldPane.add(amountField);
fieldPane.add(rateField);
fieldPane.add(numPeriodsField);
fieldPane.add(paymentField);

//Put the panels in another panel, labels on left,
//text fields on right
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
contentPane.setLayout(new BorderLayout());
contentPane.add(labelPane);
contentPane.add(fieldPane, "East");

setContentPane(contentPane);
. . .
You may be surprised to find that the labels are laid out without reference to the text fields and, in fact, are in a different panel, yet align correctly with them. This is a side effect of the layout managers used by the program.
As the diagram illustrates, the program uses two GridLayout managers, one to lay out the column of labels and one for the column of text fields. GridLayout guarantees that all of its components are the same size, so all of the text fields are the same height and all of the labels are the same height.

To get the labels and the text fields to align, the program uses a third layout manager, a BorderLayout. With just two components at East and Center, BorderLayout guarantees the columns are the same height. Thus, the labels and the text fields align.

Another way to get labels and text fields to align is to use the AWT's most flexible, complex layout manager: GridBagLayout(in the Creating a User Interface trail).

Providing a Password Field

Swing provides the JPasswordField(in the API reference documentation) class, a subclass of JTextField, to use in place of a text field when the text entered by a user is a password. For security reasons, a password field doesn't show the characters the user types. Instead the field displays another character such as an asterisk '*'.

The PasswordDemo example described in Using the SwingWorker Class uses a JPasswordField. The program brings up a small window to prompt the user to type in a password:

Here's the code from PasswordDemo that creates and sets up the password field.
JPasswordField password = new JPasswordField(10);
password.setEchoChar('#');

password.addActionListener(showSwingWorkerDialog);
The argument passed into the JPasswordField constructor indicates that the field should be 10 columns wide. By default a password field displays an asterisk '*' for each character typed. The call to setEchoChar changes it to a pound sign '#'. Finally, the code adds an action listener to the password field. The action listener's actionPerformed method gets the password typed by the user and verifies it with this code:
public void actionPerformed(ActionEvent e) {
    JPasswordField input = (JPasswordField)e.getSource();
    char[] password = input.getPassword();
    if (isPasswordCorrect(password))
        JOptionPane.showMessageDialog(f, worker.get());
    else
        JOptionPane.showMessageDialog(f,
	    new JLabel("Invalid password."));
    }
This method uses the password field's getPassword method to get the contents of the field. Note that getPassword returns a character array. Password information should not be stored or passed around in strings because strings are not secure. So don't [PENDING: or you can't] use getText or setText on a password field. Instead use getPassword or setPassword because these methods use character arrays instead of strings.

Note: The getPassword method and its companion setter, setPassword, did not exist in Swing 1.0.3 and earlier releases. In these releases, use getText and setText. Your program should store any password as a character array, and convert the value to a temporary string when calling either getText or setText.

The Text Field API

The following tables list the commonly used JTextField constructors and methods. Other methods you're likely to call are defined by the JComponent(in the API reference documentation) and Component(in the API reference documentation) classes. They include Component's setForeground, setBackground, and setFont methods. [CHECK: is that right? any other particularly useful Component/JComponent methods?] [Link to JComponent and Component discussions.]

Additionally, you might want to call some of the methods defined in JTextField's parent class, JTextComponent. Refer to the API tables in the section on text components: The Text API.

The API for using text fields falls into three categories:

Setting or Getting the Text Field's Contents
Method or Constructor Purpose

JTextField()
JTextField(String)
JTextField(String, int)
JTextField(int)
JTextField(Document, String, int)
Create a JTextField instance, initializing it to contain the specified text. The int argument sets the number of columns. This is used to compute the component's preferred width and may not be the actual number of columns displayed [CHECK].
void setText(String)
String getText()
Set or get the text displayed by the text field.

Fine Tuning the Text Field's Appearance
Method or Constructor Purpose
void setEditable(boolean)
boolean isEditable()
Set or get whether the user can edit the text in the text field.
void setForeground(Color)
Color getForeground()
Set or get the color of the text within the text field.
void setBackground(Color);
Color getBackground()
Set or get the background color of the text field.
void setFont(Font);
Font getFont()
Set or get the font used by the text field.
void setColumns(int);
int getColumns()
Set or get the number of columns displayed by the text field.
int getColumnWidth() Get the width of the text field's columns. This value is extablished implicitly by the font.
void setHorizontalAlignment(int);
int getHorizontalAlignment()
Set or get how the text is aligned horizontally within its area. You can use JTextField.LEFT, JTextField.CENTER, and JTextField.RIGHT for arguments.

Implementing the Text Field's Functionality
Method or Constructor Purpose
void addActionListener(ActionListener)
void removeActionListener(ActionListener)
Add or remove an action listener.
Document createDefaultModel() Override this method to provide the text field with a custom document.

Examples that Use Text Fields

This table shows the examples that use JTextField and where those examples are described.

Example Where Described Notes
TextDemo.java This page Uses a text field with an action listener.
TextFieldDemo.java This page Implements two different keystroke-validated fields.
PasswordDemo.java This page and Using the SwingWorkerClass Uses a password field.
ControlPane.java, Utilities.java Let's Play(in Putting It Together trail) Uses a grid bag layout to align labels with text fields. See the addParameterRow method in Utilities.java. Part of the BINGO player application.
CustomDialog.java How to Make Dialogs Includes a text field whose value is checked. Part of DialogDemo (under the More Dialogs tab).


Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages