By Tony Bevis on Thursday, 19 October 2023
Category: Java

Java programming course: 14.7 JRadioButton

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:


Running the above should result in this:

[1] The number of rows is set to zero, indicating that any number of rows could be added.

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:

You can use isSelected() to determine if a radio button is selected:

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.

Next lesson: 14.8 JComboBox

Related Posts

Leave Comments