Previous | Next | Trail Map | To 1.1 -- And Beyond! | GUI Changes: The AWT Grows Up


How to Use Radio Buttons

Radio buttons are groups of buttons in which only one button at a time can be selected. The Swing release supports radio buttons with the JRadioButton(in the API reference documentation) and ButtonGroup(in the API reference documentation) classes.

Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual button characteristics, as discussed in How to Use Buttons. For example, you can specify the text (if any) and image in a radio button.

Here is a picture of an application that has two radio buttons:


[We'll try to make the example more interesting...]


Try this:
  1. Compile and run the application. The source file is RadioButtonDemo.java.
    See Getting Started with Swing if you need help.
  2. Click Button 2.
    Button 2 becomes selected, which makes Button 1 become unselected.
  3. Look at the messages displayed at the standard output.
    This application registers a listener for each kind of event a button can send -- action, change, and item. Each time it receives an event, the application displays a message describing the event.
  4. Click Button 2 again, and look at the messages displayed at the standard output.

Often, the only event handler a radio button needs is an action listener. You can use an item listener instead if you're simply monitoring state changes, rather than acting on them. You don't need to implement a change listener unless your program needs to know every time the button's appearance changes. [check all this]


Note: If you have a strong opinion about what events should be generated by radio buttons, please let us know. For example, a radio button currently generates an action event even when the user clicks an already selected button. It probably shouldn't.

Below is the code from RadioButtonDemo.java that creates the radio buttons in the previous example and reacts to clicks.

//In initialization code:
    // Create the buttons.
    JRadioButton firstButton = new JRadioButton(first);
    firstButton.setKeyAccelerator('1'); 
    firstButton.setActionCommand(first);
    firstButton.setSelected(true);

    JRadioButton secondButton = new JRadioButton(second);
    secondButton.setKeyAccelerator('2'); 
    secondButton.setActionCommand(second);

    // Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(firstButton);
    group.add(secondButton);

    // Register a listener for the radio buttons.
    RadioListener myListener = new RadioListener();
    firstButton.addActionListener(myListener);
    firstButton.addChangeListener(myListener);
    firstButton.addItemListener(myListener);
    secondButton.addActionListener(myListener);
    secondButton.addChangeListener(myListener);
    secondButton.addItemListener(myListener);
. . .
class RadioListener implements ActionListener, //only one event type needed
			       ChangeListener, //for curiosity only
			       ItemListener {  //for curiosity only
    public void actionPerformed(ActionEvent e) {
        String factoryName = null;

        System.out.print("ActionEvent received: ");
        if (e.getActionCommand() == first) {
    	    System.out.println(first + " pressed.");
        } else {
    	    System.out.println(second + " pressed.");
        }
    }

    public void itemStateChanged(ItemEvent e) {
        System.out.println("ItemEvent received: " 
    		           + e.getItem()
    		           + " is now "
    		           + ((e.getStateChange() == ItemEvent.SELECTED)?
    			      "selected.":"unselected"));
    }

    public void stateChanged(ChangeEvent e) {
        System.out.println("ChangeEvent received from: "
    		           + e.getSource());
    }
}
See How to Use Buttons for information on the AbstractButton API that JRadioButton inherits. The only API defined by JRadioButton that you're likely to use are the constructors. JRadioButton defines seven constructors:

The arguments are straightforward:

String
Specifies the text that the radio button should display.
Icon
Specifies the image that the radio button should display. Unless you specify an image, the images defined by the look-and-feel are used.
boolean
Specifies whether the radio button is selected. By default, it's false (not selected).

For each group of radio buttons, you need to create a ButtonGroup instance and add each radio button to it. The ButtonGroup ensures that exactly one button in the group is selected. [I suspect the group can be created with no button selected.] Here are the ButtonGroup methods and constructors you're likely to use:

ButtonGroup()
Creates an instance of ButtonGroup.
add(AbstractButton)
Adds the specified button to the group.
remove(AbstractButton)
Removes the specified button from the group.


Previous | Next | Trail Map | To 1.1 -- And Beyond! | GUI Changes: The AWT Grows Up