A text field can be used to enter or display a string. JTextField is a subclass of JTextComponent . Figure 15.16 lists the constructors and methods in JTextField .
JTextField inherits JTextComponent , which inherits JComponent . Here is an example of creating a non-editable text field with red foreground color and right horizontal alignment:
JTextField jtfMessage = new JTextField( "T-Strom" ); jtfMessage.setEditable( false ); jtfMessage.setForeground(Color.red); jtfMessage.setHorizontalAlignment(SwingConstants.RIGHT);
When you move the cursor in the text field and press the Enter key, it fires an ActionEvent .
Listing 15.5 gives a program that adds a text field to the preceding example to let the user set a new message, as shown in Figure 15.17.
Listing 15.5 creates a subclass that extends RadioButtonDemo .
TextFieldDemo extends RadioButtonDemo and adds a label and a text field to let the user enter a new message. After you set a new message in the text field and press the Enter key, a new message is displayed. Pressing the Enter key on the text field triggers an action event. The listener sets a new message in messagePanel (line 33).
Instead of using the setSize method to set the size for the frame, the program uses the pack() method (line 11), which automatically sizes up the frame according to the size of the components placed in it.
The requestFocusInWindow() method (line 34) defined in the Component class requests the component to receive input focus. Thus, jtfMessage.requestFocusInWindow() (line 34) requests the input focus on jtfMessage . You will see the cursor on jtfMessage after the actionPerformed method is invoked.
Note
If a text field is used for entering a password, use JPasswordField to replace JTextField . JPasswordField extends JTextField and hides the input text with echo characters (e.g., ****** ). By default, the echo character is * . You can specify a new echo character using the setEchoChar(char) method. |