The ButtonGroup Class

The ButtonGroup class allows buttons to be logically grouped, guaranteeing that no more than one button in the group is selected at any given time. In fact, once one of the buttons is selected, the ButtonGroup ensures that exactly one button remains selected at all times. Note that this allows for an initial state (in which no button is selected) that can never be reached again once a selection is made, except programmatically.

As mentioned earlier, ButtonGroups typically hold JRadioButtons (or JRadioButtonMenuItems, discussed in Chapter 14), but this is purely a convention and is not enforced by ButtonGroup. ButtonGroup’s add( ) method takes objects of type AbstractButton, so any button type may be added—even a mix of types. Of course, adding a JButton to a ButtonGroup would not be very useful since JButtons do not have selected and deselected states. In fact, JButtons added to ButtonGroups have no effect on the state of the other buttons if they are pressed.

ButtonGroup objects do not have any visual appearance; they simply provide a logical grouping of a set of buttons. You must add buttons in a ButtonGroup to a Container and lay them out as though no ButtonGroup were being used.

It’s worth noting that some methods in the ButtonGroup class deal with AbstractButton objects and some deal with ButtonModel objects. The add( ), remove( ) , and getElements( ) methods all use AbstractButton, while the getSelection( ), isSelected( ), and setSelected( ) methods use ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.