Java Reference
In-Depth Information
Note The Box class described in Chapter 11 serves as a good container for a group of JRadioButton
components.
2.
Place a border around the container, to label the grouping. This is an optional step, but
you'll frequently want to add a border to label the group for the user. You can read more
about borders in Chapter 7.
Border border = BorderFactory.createTitledBorder("Slice Count");
aPanel.setBorder(border);
Create a ButtonGroup .
3.
ButtonGroup aGroup = new ButtonGroup();
For each selectable option, create a JRadioButton , add it to a container, and then add it
to the group.
4.
JRadioButton aRadioButton = new JRadioButton(...);
aPanel.add(aRadioButton);
aGroup.add(aRadioButton);
You might find the whole process, especially the fourth step, a bit tedious after a while,
especially when you add another step for handling selection events. The helper class shown
in Listing 5-5, with its static createRadioButtonGrouping(String elements[], String title)
method, could prove useful. It takes a String array for the radio button labels as well as the
border title, and then it creates a set of JRadioButton objects with a common ButtonGroup in a
JPanel with a titled border.
Listing 5-5. Initial Support Class for Working with JRadioButton
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class RadioButtonUtils {
private RadioButtonUtils() {
// Private constructor so you can't create instances
}
public static Container createRadioButtonGrouping (String elements[],
String title) {
JPanel panel = new JPanel(new GridLayout(0, 1));
// If title set, create titled border
if (title != null) {
Border border = BorderFactory.createTitledBorder(title);
panel.setBorder(border);
}
 
Search WWH ::




Custom Search