Java Reference
In-Depth Information
Fig. 12.20
|
Testing
RadioButtonFrame
. (Part 2 of 2.)
Lines 35-42 (Fig. 12.19) in the constructor create four
JRadioButton
objects and add
them to the
JFrame
. Each
JRadioButton
is created with a constructor call like that in line
35. This constructor specifies the label that appears to the right of the
JRadioButton
by
default and the initial state of the
JRadioButton
. A
true
second argument indicates that
the
JRadioButton
should appear
selected
when it's displayed.
Line 45 instantiates
ButtonGroup
object
radioGroup
. This object is the “glue” that
forms the logical relationship between the four
JRadioButton
objects and allows only one
of the four to be selected at a time. It's possible that no
JRadioButton
s in a
ButtonGroup
are selected, but this can occur
only
if
no
preselected
JRadioButton
s are added to the
But-
tonGroup
and the user has
not
selected a
JRadioButton
yet. Lines 46-49 use
ButtonGroup
method
add
to associate each of the
JRadioButton
s with
radioGroup
. If more than one
selected
JRadioButton
object is added to the group, the selected one that was added
first
will be selected when the GUI is displayed.
JRadioButton
s, like
JCheckBox
es, generate
ItemEvent
s when they're
clicked
. Lines
59-66 create four instances of inner class
RadioButtonHandler
(declared at lines 70-85).
In this example, each event-listener object is registered to handle the
ItemEvent
generated
when the user clicks a particular
JRadioButton
. Notice that each
RadioButtonHandler
object is initialized with a particular
Font
object (created in lines 52-55).
Class
RadioButtonHandler
(line 70-85) implements interface
ItemListener
so it can
handle
ItemEvent
s generated by the
JRadioButton
s. The constructor stores the
Font
object it receives as an argument in the event-listener object's instance variable
font
(declared at line 72). When the user clicks a
JRadioButton
,
radioGroup
turns off the pre-
viously selected
JRadioButton
, and method
itemStateChanged
(lines 80-84) sets the font
in the
JTextField
to the
Font
stored in the
JRadioButton
's corresponding event-listener
object. Notice that line 83 of inner class
RadioButtonHandler
uses the top-level class's
textField
instance variable to set the font.
Event Handling
A combo box
(sometimes called a
drop-down list
) enables the user to select
one
item from
a list (Fig. 12.22). Combo boxes are implemented with class
JComboBox
, which extends