JRadioButton
The JRadioButton class allows the selection of one option in a group of mutually exclusive options; that is, where there are two or more possible options but only one option should ever be chosen. To use JRadioButton objects you need to assign them to a ButtonGroup object which manages the mutual exclusion for you:
// Define the options
JRadioButton redOption = new JRadioButton("Red");
JRadioButton greenOption = new JRadioButton("Green");
JRadioButton blueOption = new JRadioButton("Blue");
// Assign the options to a group
ButtonGroup group = new ButtonGroup();
group.add(redOption);
group.add(greenOption);
group.add(blueOption);
// Show the options in a grid
JPanel colourPanel = new JPanel(new GridLayout(0, 1));
colourPanel.add(redOption);
colourPanel.add(greenOption);
colourPanel.add(blueOption);
// Add the grid to the main panel
panel.add(colourPanel);
- The first section instantiates three
JRadioButtonobjects, corresponding to the colours red, green and blue - The second section adds each of the radio button objects to a
ButtonGroupobject, which will serve to enforce the fact that only one colour should ever be selected - The third section places the radio buttons below each other in a one-column grid[1]
- The fourth section adds the grid to the outer panel
Running the above should result in this:
If you click in any of the selectable circles, then that item will be selected and the previously selected option (if any) will be de-selected. It is generally a good idea, unless it is entirely optional to select any option, to programmatically set one of the options as a default using the setSelected() method:
blueOption.setSelected(true);
You can use isSelected() to determine if a radio button is selected:
boolean redWanted = redOption.isSelected();
There is no straightforward way of determining which radio button within a group has been selected without checking each in turn.
It is important to note the difference between a group of JRadioButton objects and a group of JCheckBox objects. Whereas radio buttons indicate a mutually exclusive set of options, if you have a series of check boxes then they each operate independently, and any combination of check boxes may be selected or de-selected. You therefore don't require a ButtonGroup object for your check boxes.
As an example, suppose you want the user to select the size and toppings required on a pizza:
The size (small, medium or large) should be selectable with a group of radio buttons because a single pizza can only be one size.
The toppings (chicken, pork, onions, mushrooms, etc.) should be selectable with a group of check boxes because you can have any combination.