Trail: Creating a GUI with JFC/Swing
Lesson: Using Swing Components
How to Use Text Fields
How to Use Text Fields
A text field is a basic text control that lets the user enter a small amount of text. When the user indicates that text entry is complete (usually by pressing Enter), the text field fires an action event. If you need to obtain more than one line of input from the user, you should use a text area instead.

The Swing API provides several classes for components that are either varieties of text fields or that include text fields.

JTextField What this section covers: basic text fields.
JFormattedTextField A JTextField subclass that allows you to specify the legal set of characters the user can enter. See How to Use Formatted Text Fields.
JPasswordField A JTextField subclass that doesn't show the characters the user types. See How to Use Password Fields.
JComboBox Can be editable, and provides a menu of strings to choose from. See How to Use Combo Boxes.
JSpinner Combines a formatted text field with a couple of small buttons that let the user choose the previous or next available value. See How to Use Spinners.

The following example displays a basic text field and a text area. The text field is editable; the text area isn't. When the user presses Enter in the text field, the program copies the text field's contents to the text area, and then selects all the text in the text field.

A snapshot of TextDemo

[PENDING: This snapshot will be updated.]

You can run TextDemo using JavaTM Web Start. The source code is in TextDemo.java. Here's the code that creates and sets up the text field:

textField = new JTextField(20);
textField.addActionListener(this);
The integer argument passed to the JTextField constructor, 20 in the example, indicates the number of columns in the field. This number is used along with metrics provided by the field's current font to calculate the field's preferred width. It does not limit the number of characters the user can enter. To do that, you can either use a formatted text field or a document listener, as described in Text Component Features.

Note: We encourage you to specify the number of columns for each text field. If you don't specify the number of columns or a preferred size, then the field's preferred size changes whenever the text changes, which can result in unwanted layout updates.

The next line of code registers a TextDemo object as an action listener for the text field. Here's the actionPerformed method that handles action events from the text field:

private final static String newline = "\n";
...
public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}
Notice the use of JTextField's getText method to retrieve the text currently contained by the text field. The text returned by this method does not include a newline character for the Enter key that fired the action event.

You've seen how a basic text field can be used. Because JTextField inherits from JTextComponent, it's very flexible and can be customized almost any way you like. For example, you can add a document listener or document filter to be notified when the text changes and (in the filter case) modify the text field accordingly. Information on text components is in Text Component Features Before customizing a JTextField, however, make sure that one of the other components based on text fields won't do the job for you.

Often, text fields are paired with labels that describe the text fields. See Examples that Use Text Fields for pointers to examples of creating these pairs.

The Text Field API

The following tables list the commonly used JTextField constructors and methods. Other methods you are likely to call are defined in JTextComponent. Refer to The Text Component API.

You might also invoke methods on a text field that it inherits from its other ancestors, such as setPreferredSize, setForeground, setBackground, setFont, and so on. See The JComponent Class for tables of commonly used inherited methods.

The API for using text fields falls into these categories:

Setting or Getting the Field's Contents
Method or Constructor Purpose
JTextField()
JTextField(String)
JTextField(String, int)
JTextField(int)
Create a text field. When present, the int argument specifies the desired width in columns. The String argument contains the field's initial text.
void setText(String)
String getText()
(defined in JTextComponent)
Set or get the text displayed by the text field.

Fine Tuning the Field's Appearance
Method Purpose
void setEditable(boolean)
boolean isEditable()
(defined in JTextComponent)
Set or get whether the user can edit the text in the text field.
void setColumns(int);
int getColumns()
Set or get the number of columns displayed by the text field. This is really just a hint for computing the field's preferred width.
void setHorizontalAlignment(int);
int getHorizontalAlignment()
Set or get how the text is aligned horizontally within its area. You can use JTextField.LEADING, JTextField.CENTER, and JTextField.TRAILING for arguments.

Implementing the Field's Functionality
Method Purpose
void addActionListener(ActionListener)
void removeActionListener(ActionListener)
Add or remove an action listener.
void selectAll()
(defined in JTextComponent)
Select all characters in the text field.

Examples that Use Text Fields

This table shows a few of the examples that use JTextField and where those examples are described. For examples of code that's similar among all varieties of text fields, such as dealing with layout, also look at the example lists for related components such as formatted text fields and spinners.

Example Where Described Notes
TextDemo This section An application that uses a basic text field with an action listener.
DialogDemo How to Make Dialogs CustomDialog.java includes a text field whose value is checked. You can bring up the dialog by clicking the More Dialogs tab, selecting the Input-validating dialog radio button, and then clicking the Show it! buton.
TextSamplerDemo Using Text Components Lays out label-text field pairs using a GridBagLayout and a convenience method:
addLabelTextRows(JLabel[] labels,
		 JTextField[] textFields,
		 GridBagLayout gridbag,
		 Container container)
TextInputDemo How to Use Formatted Text Fields Lays out label-text field pairs using a SpringLayout and a SpringUtilities convenience method:
makeCompactGrid(Container parent,
                int rows, int cols,
                int initialX, int initialY,
                int xPad, int yPad)

Previous page: How to Use Text Areas
Next page: How to Use Tool Bars