Java Reference
In-Depth Information
generated the event each time actionPerformed is called. The event source is the compo-
nent with which the user interacted. When the user presses Enter while a text field or the
password field has the focus , the system creates a unique ActionEvent object that contains
information about the event that just occurred, such as the event source and the text in the
text field. The system passes this ActionEvent object to the event listener's actionPer-
formed method. Line 56 declares the String that will be displayed. The variable is initialized
with the empty string —a String containing no characters. The compiler requires the vari-
able to be initialized in case none of the branches of the nested if in lines 59-76 executes.
ActionEvent method getSource (called in lines 59, 64, 69 and 74) returns a reference
to the event source. The condition in line 59 asks, “Is the event source textField1 ?” This
condition compares references with the == operator to determine if they refer to the same
object. If they both refer to textField1 , the user pressed Enter in textField1 . Then, lines
60-61 create a String containing the message that line 79 displays in a message dialog.
Line 61 uses ActionEvent method getActionCommand to obtain the text the user typed in
the text field that generated the event.
In this example, we display the text of the password in the JPasswordField when the
user presses Enter in that field. Sometimes it's necessary to programatically process the
characters in a password. Class JPasswordField method getPassword returns the pass-
word's characters as an array of type char .
Class TextFieldTest
Class TextFieldTest (Fig. 12.10) contains the main method that executes this application
and displays an object of class TextFieldFrame . When you execute the application, even
the uneditable JTextField ( textField3 ) can generate an ActionEvent . To test this, click
the text field to give it the focus, then press Enter . Also, the actual text of the password is
displayed when you press Enter in the JPasswordField . Of course, you would normally
not display the password!
1
// Fig. 12.10: TextFieldTest.java
2
// Testing TextFieldFrame.
3
import javax.swing.JFrame;
4
5
public class TextFieldTest
6
{
7
public static void main(String[] args)
8
{
9
TextFieldFrame textFieldFrame = new TextFieldFrame();
10
textFieldFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
11
textFieldFrame.setSize( 350 , 100 );
12
textFieldFrame.setVisible( true );
13
}
14
} // end class TextFieldTest
Fig. 12.10 | Testing TextFieldFrame . (Part 1 of 2.)
 
Search WWH ::




Custom Search