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 , 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 ven 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 ButtonModel objects.

ButtonGroup Properties
The buttonCount property is the number of buttons in the group. The elements property is an Enumeration of the AbstractButton objects contained by the group. The selection property contains the ButtonModel of the currently selected button.
Voting with a Button Group
The following example demonstrates the use of a ButtonGroup to ensure that only a single selection is made from a list of choices. Listeners are added to the buttons to show which events are fired each time a new button is selected.

Here is the ButtonGroup example source code you can use freely.

// SimpleButtonGroupExample.java
//
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

// A ButtonGroup voting booth
public class SimpleButtonGroupExample {

  public static void main(String[] args) {
    // Some choices
    JRadioButton choice1, choice2, choice3;
    choice1 = new JRadioButton("Bach: Well Tempered Clavier, Book I");
    choice1.setActionCommand("bach1");
    choice2 = new JRadioButton("Bach: Well Tempered Clavier, Book II");
    choice2.setActionCommand("bach2");
    choice3 = new JRadioButton("Shostakovich: 24 Preludes and Fugues");
    choice3.setActionCommand("shostakovich");

    // A group that ensures we vote for only one
    final ButtonGroup group = new ButtonGroup( );
    group.add(choice1);
    group.add(choice2);
    group.add(choice3);

    // A simple ActionListener, showing each selection using the ButtonModel
    class VoteActionListener implements ActionListener {
      public void actionPerformed(ActionEvent ev) {
        String choice = group.getSelection( ).getActionCommand( );
        System.out.println("ACTION Choice Selected: " + choice);
      }
    }

    // A simple ItemListener, showing each selection and deselection
    class VoteItemListener implements ItemListener {
      public void itemStateChanged(ItemEvent ev) {
        boolean selected = (ev.getStateChange( ) == ItemEvent.SELECTED);
        AbstractButton button = (AbstractButton)ev.getItemSelectable( );
        System.out.println("ITEM Choice Selected: " + selected +
                           ", Selection: " + button.getActionCommand( ));
      }
    }

    // Add listeners to each button.
    ActionListener alisten = new VoteActionListener( );
    choice1.addActionListener(alisten);
    choice2.addActionListener(alisten);
    choice3.addActionListener(alisten);

    ItemListener ilisten = new VoteItemListener( );
    choice1.addItemListener(ilisten);
    choice2.addItemListener(ilisten);
    choice3.addItemListener(ilisten);

    // Throw everything together.
    JFrame frame = new JFrame( );
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = frame.getContentPane( );
    c.setLayout(new GridLayout(0, 1));
    c.add(new JLabel("Vote for your favorite prelude & fugue cycle"));
    c.add(choice1);
    c.add(choice2);
    c.add(choice3);
    frame.pack( );
    frame.setVisible(true);
  }
}

We first create three radio buttons and add them to a button group. Then, we define an ActionListener and an ItemListener to print out some information each time a selection is made. We add both listeners to each button. The rest of the code is just layout.

When executed, the initial selection of a radio button produces the following output:

ITEM Choice Selected: true, Selection: shostakovich
ACTION Choice Selected: shostakovich
Changing the selection causes two item events to be fired, showing which button was toggled off and which was toggled on:

ITEM Choice Selected: false, Selection: shostakovich
ITEM Choice Selected: true, Selection: bach1
ACTION Choice Selected: bach1
ButtonGroup Constructor

public ButtonGroup( )

Create an empty group.

ButtonGroup Methods

public void add(AbstractButton b)

Add a button to the group. If there is no selected button in the group, and the supplied button is selected, it becomes the group’s selection. (Conversely, if there is already a selected button, adding a selected button does not change the selection; Swing adds the button to the group but if necessary deselects it first.)

public void remove(AbstractButton b)

Remove a button from the group. If the removed button was the currently selected button, the group’s selection is set to null.

public void setSelected(ButtonModel m, boolean b)

Select the given button if the boolean parameter is true. If there was a previously selected button in the group, it is deselected. Calling this method with a false argument has no effect.

public boolean isSelected(ButtonModel m)

This method indicates whether the given button is the group’s currently selected button.