Page 759 - Introduction to Programming with Java: A Problem Solving Approach
P. 759
17.13 JradioButton Component 725 selected radio button, no change occurs (i.e., the clicked button remains selected). In contrast, if a user clicks
a selected check box, the check box changes its state from selected to unselected.
Implementation
To create a JRadioButton component, call the JRadioButton constructor like this: JRadioButton <JRadioButton-reference> =
new JRadioButton(<label>, <selected>);
The label argument specifies the text that appears at the right of the radio button’s circle. If the label argu- ment is omitted, then no text appears at the right of the radio button’s circle. The selected argument speci- fies whether the radio button is initially selected—true means selected, false means unselected. If the selected argument is omitted, then the radio button is initially unselected.
This example shows how we created the standard and custom radio buttons in the installation- options program:
standard = new JRadioButton("Standard (recommended)", true);
custom = new JRadioButton("Custom");
To enable the only-one-button-selected-at-a-time functionality of a radio button group, create a ButtonGroup object and add individual radio button components to it. Here’s how:
...
< ButtonGroup-reference>.add(<last-button-in-group>);
The following example shows how we created the radio button group for the standard and custom
radio buttons in the installation-options program:
ButtonGroup rbGroup = new ButtonGroup();
rbGroup.add(standard);
rbGroup.add(custom);
After adding radio buttons to a radio button group, you still have to add them to a container. Radio buttons work the same as other components in terms of adding them to a container. Call the container’s add method like this:
add(<first-button-in-group>); ... add(<last-button-in-group>);
That’s a lot of adding. You need to add each radio button twice—once to a radio button group and once to a container. If you like shortcuts, you might be thinking, Why does Java make you add the individual radio buttons to the container? Why are they not added automatically when the radio button group is added? Add- ing the buttons separately from the button group gives you freedom in positioning the buttons. If you wanted to, you could even put them in different panels.
Since the JRadioButton class begins with a J, you can correctly assume that it’s defined in the javax.swing package. But what about the ButtonGroup class? Even though it doesn’t begin with a J, it’s also defined in the javax.swing package.
ButtonGroup <ButtonGroup-reference> = new ButtonGroup(); < ButtonGroup-reference>.add(<first-button-in-group>);
Apago PDF Enhancer