16.6. Passing Strings to Applets

 
[Page 504 ( continued )]

15.6. Text Fields

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 .

Figure 15.16. JTextField enables you to enter or display a string.

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.

Figure 15.17. A label and a text field are added to set a new message.
(This item is displayed on page 505 in the print version)


Listing 15.5 creates a subclass that extends RadioButtonDemo .

Listing 15.5. TextFieldDemo.java
(This item is displayed on pages 504 - 505 in the print version)


[Page 505]

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.


[Page 506]

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.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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