Chapter 12 Graphical User Interface Components: Part 1 (Free web host)
Chapter 12 Graphical User Interface Components: Part 1 667 79 // set text field font 80 field.setFont( 81 new Font( “Serif”, valBold + valItalic, 14 ) ); 82 } 83 84 } // end private inner class CheckBoxHandler 85 86 } // end class CheckBoxTest Fig. 12.11 Program that creates two JCheckBoxbuttons (part 3 of 3). After the JTextFieldis created and initialized, line 27 sets the font of the JText- Field to Serif, PLAIN style and 14-point size. Next, the constructor creates two JCheckBox objects with lines 31 and 34. The String passed to the constructor is the check box label that appears to the right of the JCheckBoxby default. When the user clicks a JCheckBox, an ItemEventoccurs that can be handled by an ItemListener (any object of a class that implements interface ItemListener). An ItemListener must define method itemStateChanged. In this example, the event handling is performed by an instance of inner class CheckBoxHandler(lines 56 84). Lines 38 40 create an instance of class CheckBoxHandler and register it with method addItemListener as the ItemListener for both the bold and italic JCheckBoxes. Method itemStateChanged(lines 61 82) is called when the user clicks either the boldor the italiccheckbox. The method uses event.getSource()to determine which JCheckBox was clicked. If it was JCheckBoxbold, the if/elsestructure at lines 66 69 uses ItemEvent method getStateChange to determine the state of the button (ItemEvent.SELECTED or ItemEvent.DESELECTED). If the state is selected, integer valBold is assigned Font.BOLD; otherwise, valBold is assigned Font.PLAIN. A similar if/else structure is executed if JCheckBox italic is clicked. If the italicstate is selected, integer valItalicis assigned Font.ITALIC; otherwise, valItalic is assigned Font.PLAIN. The sum of valBold and valItalicis used at lines 80 81 as the style of the new font for the JTextField. Radio buttons (defined with class JRadioButton) are similar to check boxes in that they have two states selected and not selected (also called deselected). However, radio buttons normally appear as a group in which only one radio button can be selected at a time. Selecting a different radio button in the group automatically forces all other radio buttons in the group to be deselected. Radio buttons are used to represent a set of mutually exclusive Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01