How to Use Text Fields

 <  Day Day Up  >  

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 [a]

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 (page 221).

JPasswordField

A JTextField subclass that doesn't show the characters the user types. See How to Use Password Fields (page 297).

JComboBox

Can be editable, and provides a menu of strings to choose from. See How to Use Combo Boxes (page 176).

JSpinner

Combines a formatted text field with several small buttons that let the user choose the previous or next available value. See How to Use Spinners (page 357).

[a] See the JTextField API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTextField.html.

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

Figure 85. The TextDemo application with two Groucho Marx quotations.

graphics/07fig85.gif

graphics/cd_icon.gif

You can run TextDemo using Java Web Start or compile and run the example yourself. [194] Here's the code from TextDemo.java that creates and sets up the text field:

[194] To run TextDemo using Java Web Start, click the TextDemo link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#TextDemo .

 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 use either a formatted text field or a document listener, as described in Text Component Features (page 64) in Chapter 3.

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 (page 64). 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 (page 426) for pointers to examples of creating these pairs.

The Text Field API

Tables 96 through 98 list the commonly used JTextField constructors and methods. Other methods you are likely to call are defined in JTextComponent and listed in The Text Component API (page 77). Also refer to the JTextField API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTextField.html.

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 (page 53) in Chapter 3 for tables of commonly used inherited methods.

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

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

Table 98. 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 (page 187)

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 (page 60)

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 (page 221)

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) 
 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net