Java Reference
In-Depth Information
The JTextField Component
The JTextField is the basic data entry field. It allows the user to enter plain text up to a speci-
fied length. Here's a simple constructor for the JTextField with a size of 15 columns:
JTextField zipCode = new JTextField(15);
Other constructors for the JTextField allow you to specify a default value to be displayed
in the text field, and a Document to validate data entry (data validation will be covered in the
next subsection).
A very simple application to demonstrate the use of JLabel s and JTextField s is shown in
Listing 8-5, and the GUI that this creates is shown in Figure 8-16. A JButton has been included
in the GUI to allow you to experiment with transferring focus away from the JTextField and
then use the mnemonic to transfer focus back again.
Listing 8-5. Demonstration of JLabel and JtextField Components
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class MyFrame extends JFrame {
public static void main(String[] args) throws Exception {
new MyFrame().setVisible(true);
}
public MyFrame() throws Exception {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JLabel zipCodeLabel = new JLabel("Zip code");
JTextField zipCode = new JTextField(15);
zipCodeLabel.setDisplayedMnemonic('Z');
zipCodeLabel.setLabelFor(zipCode);
this.add(zipCodeLabel);
this.add(zipCode);
this.add(new JButton("A button for focus"));
pack();
}
}
Figure 8-16. Demonstration of JLabel and JtextField components
Search WWH ::




Custom Search