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(in the API reference documentation) class instead. See the PasswordDemo example described in Using the SwingWorker Class for an example of using a JPasswordField.

If you want to provide some strings for the user 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 loan calculator shown in the following figure uses four JTextField instances. Each JTextField has an accompanying JLabel that describes it. The user enters loan information into the first three text fields, then presses the return key. The program computes the monthly payment and displays the result in the fourth text field.


Try this:
  1. Compile and run the application. The source file is LoanCalc.java.
    See Getting Started with Swing if you need help.
  2. Enter information into the text fields and see the results.
    If you enter invalid data, the program displays an error message. This program uses a class called java.text.NumberFormat to format and parse the numbers in the text fields. Because NumberFormat is locale-sensitive, it is covered in the internationalization trail. See Number Formatting(in the Internationalization trail) for more information.
  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.

Below is the code from LoanCalc.java that creates the text fields in the previous example.

setUpFormatters();
. . .
//Create the text fields and set them up
amountField = new JTextField(moneyFormatter.format(amount), 10);
amountField.addActionListener(new TextFieldListener(moneyFormatter));

rateField = new JTextField(percentFormatter.format(rate), 10);
rateField.addActionListener(new TextFieldListener(percentFormatter));
 
numPeriodsField = new JTextField(integerFormatter.format(numPeriods), 10);
numPeriodsField.addActionListener(new TextFieldListener(integerFormatter));
 
paymentField = new JTextField(moneyFormatter.format(payment), 10);
paymentField.setEditable(false);
paymentField.setForeground(Color.red);

. . .

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 lable 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).

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.]

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 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.

Handling Events from a Text Field
Method or Constructor Purpose
addActionListener(ActionListener) Provide the text field with an ActionListener.

Examples that Use JTextField

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

Example Where Described Notes
LoanCalc.java This page. Uses box layouts to align labels with text fields.
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).
EeyoreQuotes.java How to Use Text Components Contains several text components, including a JTextField and a JPasswordField.


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