Java Reference
In-Depth Information
Tutorial: Swing versus AWT
JCheckBoxes can be grouped just like Checkboxes, however, the class is ButtonGroup not CheckBoxGroup. Again, the
Swing implementation of a checkbox group is very similar to AWT but there is a twist: the checkboxes do not become
round in Swing. Now this may sound minor, but it is a standard that radio buttons (round check boxes) are used to
indicate that only one item can be selected from the group. So, to abide by this standard, we need to use JRadioButton,
not JCheckBox.
1.
In the Visual Editor, delete the JCheckBox and add three JRadioButtons called empAppRB,
shipAppRB, sortAppRB with the same text and positioning as the checkboxes in
AppOptions.
Notice that the class has a new warning message. Even though you deleted the checkbox from the frame, RAD left
the import JCheckBox statement in the source code. Since the JCheckBox is never used, the import statement is not
needed and RAD flags the statement with a warning. (One would think that because RAD is smart enough to know
that the statement isn't needed, it would have been smart enough to delete the statement. Oh well.)
2.
Assign the same mnemonic and toolTipText property values to shipAppRB that were
assigned to the deleted JCheckBox in steps 10 and 13 above.
3.
In the Visual Editor palette, click on Choose a Bean.
4.
In the Choose a Bean window, begin typing ButtonGroup and when it appears in the
Matching types pane, click on it to select it.
5.
Click the OK button.
6.
In Visual Editor, click to the right of the JFrame and accept the default name.
The variable buttonGroup will be placed in the Design pane. As with AWT checkboxes, you will have to add
code to tie the radio buttons to the button group. However, instead of changing each checkbox's property, the
JRadioButtons are added to the ButtonGroup.
7.
In the getButtonGroup method, make the radio buttons part of the button group by adding
the following after the ButtonGroup object is assigned to the variable buttonGroup.
buttonGroup.add(empAppRB);
buttonGroup.add(shipAppRB);
buttonGroup.add(sortAppRB);
8.
In the getJContentPane method, after sortAppRB is added to the content pane, make the
button group part of the content pane by adding getButtonGroup(); .
9.
Run TNTSwing.
Click the radio buttons and prove that only one can be selected.
To finish the Swing implementation, we must tie the action listener to the radio buttons and write the code for
the actionPerformed.
10.
Add the action listener to each button by inserting the following statements in the
appropriate getXXXAppRB method:
empAppRB.addActionListener(this);
shipAppRB.addActionListener(this);
sortAppRB.addActionListener(this);
 
Search WWH ::




Custom Search