O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required