The
ButtonGroupcomponent manages the selected/unselected state for a set of buttons. For the group, theButtonGroupinstance guarantees that only one button can be selected at a time.Initially, all buttons managed by a
ButtonGroupinstance are unselected.How to Use ButtonGroup Features
You can use
In general, you will typically follow these steps to write code that uses aButtonGroupwith any set of objects that inherit fromAbstractButton. Typically a button group contains instances ofJRadioButton, JRadioButtonMenuItem, orJToggleButton. It would not make sense to put an instance ofJButtonorJMenuItemin a button group becauseJButtonandJMenuItemdo not implement the select/deselect button state.ButtonGroupcomponent.
- Subclass
JFrame- Call
ContextPanetogether with a layout manager- Declare and configure a set of radio buttons or toggle buttons
- Instantiate a
ButtonGroupobject- Call the
addmethod on that buttongroup object in order to add each button to the group.For details and a code example, see How to Use Radio Buttons. It shows how to use a
ButtonGroupcomponent to group a set of RadioButtons set into a JPanel.The ButtonGroup API
Commonly Used Button Group Constructors/Methods Constructor or Method Purpose ButtonGroup() Create a ButtonGroupinstance.void add(AbstractButton)
void remove(AbstractButton)Add a button to the group, or remove a button from the group. public ButtonGroup getGroup()
(inDefaultButtonModel)Get the ButtonGroup, if any, that controls a button. For example:
ButtonGroup group = ((DefaultButtonModel)button.getModel()).getGroup();public ButtonGroup clearSelection() Clears the state of selected buttons in the ButtonGroup. None of the buttons in the ButtonGroup are selected . ButtonGroup Examples
The following demonstration application uses the ButtonGroup component to group radio buttons displaying on a Window.
Example Where Described Notes RadioButtonDemoHow to Use Radio Buttons Uses radio buttons to determine which of five images it should display.