Chapter 12 Graphical User Interface Components: Part 1 (Dedicated web hosting)
Chapter 12 Graphical User Interface Components: Part 1 659 Fig. 12.7 Demonstrating JTextFields and JPasswordFields (part 4 of 4). Lines 12 13 declare three references for JTextFields (textField1, textField2 and textField3) and a JPasswordField (passwordField). Each of these is instantiated in the constructor (line 16 50). Line 24 defines JTextField textField1 with 10 columns of text. The width of the text field will be the width in pixels of the average character in the text field s current font multiplied by 10. Line 25 adds textField1to the content pane. Line 28 defines textField2with the initial text “Entertexthere”to display in the text field. The width of the text field is determined by the text. Line 29 adds textField2to the content pane. Line 33 defines textField3and call the JTextFieldconstructor with two arguments the default text “Uneditabletextfield”to display in the text field and the number of columns (20). The width of the text field is determined by the number of columns specified. Line 34 uses method setEditable(inherited into JTextFieldfrom class JTextComponent) to indicate that the user cannot modify the text in the text field. Line 35 adds textField3to the content pane. Line 38 defines JPasswordField passwordField with the text “Hidden text” to display in the text field. The width of the text field is determined by the text. Notice that the text is displayed as a string of asterisks when the program executes. Line 39 adds passwordFieldto the content pane. For the event-handling in this example, we defined inner class TextFieldHandler (lines 62 92), which implements interface ActionListener(class TextFieldHandler is discussed shortly). Thus, every instance of class TextFieldHandler is an ActionListener. Line 42 defines an instance of class TextFieldHandler and assigns it to reference handler. This one instance will be used as the event-listener object for the JTextFields and the JPasswordFieldin this example. Lines 43 46 are the event registration statements that specify the event listener object for each of the three JTextFields and for the JPasswordField. After these statements execute, the object to which handler refers is listening for events (i.e., it will be notified when an event occurs) on these four objects. The program calls JTextField method addActionListenerto register the event for each component. Method addAction- Listener receives as its argument an ActionListener object. Thus, any object of a class that implements interface ActionListener (i.e., any object that is an Action Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01