Java Reference
In-Depth Information
Radio buttons are created the same way check boxes are created. Consider the following
statements:
private JRadioButton redRB, greenRB, blueRB;
//Line 1
redRB = new JRadioButton("Red");
//Line 2
greenRB = new JRadioButton("Green");
//Line 3
blueRB = new JRadioButton("Blue");
//Line 4
The statement in Line 1 declares redRB , greenRB , and blueRB to be reference variables
of the JRadioButton type. The statement in Line 2 instantiates the object redRB and
assigns it the label "Red" . Similarly, the statements in Lines 3 and 4 instantiate the objects
greenRB and blueRB and with the labels "Green" and "Blue" , respectively.
As with check boxes, we create and place radio buttons in the content pane of the applet.
However, in this case, to force the user to select only one radio button at a time, we
create a button group and group the radio buttons. Consider the following statements:
private ButtonGroup ColorSelectBGroup;
//Line 5
ColorSelectBGroup = new ButtonGroup();
//Line 6
ColorSelectBGroup.add(redRB);
//Line 7
ColorSelectBGroup.add(greenRB);
//Line 8
ColorSelectBGroup.add(blueRB);
//Line 9
The statements in Lines 5 and 6 create the object ColorSelectBGroup , and the
statements in Lines 7, 8, and 9 add the radio buttons redRB , greenRB , and blueRB to
this object. The statements in Lines 1 through 9 create and group the radio buttons, as
shown in Figure 12-14.
1
2
FIGURE 12-14 Radio buttons
Because the radio buttons redRB , greenRB , and blueRB are grouped, the user can select
only one of these buttons. Similarly to JCheckBox , JRadioButton also generates an
ItemEvent .
So we
use
the
and
its method
interface
ItemListener
itemStateChanged to handle the events.
In the following example, we start with the applet we created in the section JCheckBox and
add three radio buttons so that the text color can be selected from the list: red, green, or blue.
Grouping buttons enforces the constraint that only one radio button can be selected at
any time. This also affects how you write the event handler. Because only one button can
Search WWH ::




Custom Search