Java: Radio Buttons and Button Groups

Radio buttons (javax.swing.JRadioButton) are used in groups (java.awt.ButtonGroup) where at most one can be selected.

A button group's purpose is to control which button is selected, and has nothing to do with the GUI.

Part I - Creating radio buttons, button groups, and adding them to a GUI

Common JRadioButton constructors and methods

boolean b; String label; JRadioButton rb;
JRadioButton
rb =new JRadioButton(label) Creates unselected radio button.
rb =new JRadioButton(label, b)Creates radio button boolean b is boolean state.
b = rb.isSelected(); Returns true if that button is selected.
 rb.setSelected(b); Sets selected status to b (true/false).
 rb.addActionListener(actionListener); Action listener called when button is selected.
 rb.addItemListener(itemListener); Item listener called when button is selected/deselected.

Common ButtonGroup constructors and methods

The most common method used for a button group is add(), but you might sometimes want to deselect all of them. Assume:
JRadioButton rb;  ButtonGroup bgroup;
JRadioButton
bg =new ButtonGroup(); Creates a radio button group.
 bgroup.add(rb); Adds a button to a radio button group.
 bgroup.clearSelection(); Sets all radio buttons to the unselected state.

Example 1 - Creating radio buttons, a button group, and displaying them

  • The program below created this window. The buttons work but do nothing.
  • Lines 14-23 create three radio buttons and add them to a group.
  • Lines 25-34 show a typical GUI button layout using on a panel with a titled, etched border.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
// File: RadioDemo1.java - Demo radio button creation, grouping, layout.
// Version: 2002-02-25 (Sicilia), minor updates 2009-01-01
// Author: Fred Swartz, Placed in public domain.

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

///////////////////////////////////////////////////////////////// RadioDemo1
class RadioDemo1 extends JFrame {
    //========================================================== constructor
    RadioDemo1() {
        //... Create the buttons.
        JRadioButton yesButton   = new JRadioButton("Yes", true);
        JRadioButton noButton    = new JRadioButton("No");
        JRadioButton maybeButton = new JRadioButton("Maybe");

        //... Create a button group and add the buttons.
        ButtonGroup bgroup = new ButtonGroup();
        bgroup.add(yesButton);
        bgroup.add(noButton);
        bgroup.add(maybeButton);
        
        //... Arrange buttons vertically in a panel
        JPanel radioPanel = new JPanel();
        radioPanel.setLayout(new GridLayout(3, 1));
        radioPanel.add(yesButton);
        radioPanel.add(noButton);
        radioPanel.add(maybeButton);
        
        //... Add a titled border to the button panel.
        radioPanel.setBorder(BorderFactory.createTitledBorder(
                   BorderFactory.createEtchedBorder(), "Married?"));

        //... Set window attributes.
        setContentPane(radioPanel);  // Button panel is only content.
        pack();                      // Layout window.
    }
    
    //================================================================= main
    public static void main(String[] args) {
        JFrame window = new RadioDemo1();
        window.setTitle("RadioDemo1");  // But window is too small to show it!
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLocationRelativeTo(null);  // Center window.
        window.setVisible(true);
    }
}

Part II - Controlling your program with radio buttons with listeners, etc

There are many ways to use radio buttons. The easiest to test explicitly from other code. The most common way is to Actions or an ActionListener so that each user click on them will execute your listener.

  1. Recommended: Test. During execution, test the radio button with isSelected().
  2. Recommended: ActionListener. In the setup phase, add an action listener with addActionListener(...). ActionListeners are called when a radio button is selected.
  3. ItemListener. In the setup phase, add an item listener with addItemListener. ItemListeners are called both when the radio button is selected and (automatically) deselected.

Listeners

  • The button's action listener is called, even if the button is already selected.
  • Two item listeners are called, one for the button that is deselected and the listener for the button that is selected. However, if the button the user clicks on is already selected (ie, nothing changes) no item listeners are called (unlike action listeners).
  • If your program uses setSelected(true) to select a radio button, the item listeners are called just as if the user had clicked it, but no action listener is called.

Most programs don't need the extra complexity of item listeners.

Part III - Optional - A convenience class

Define a class to ease your work. Java is designed to be general, and has few features that help with standard situations. Good programmers typically build up a library of classes that help them to their job, and use other pre-defined class libraries when it is convenient. You may have noticed that the above program requires quite a few lines of code to do some simple things. Here is a class I wrote to make using radio buttons simpler. You are free to use it or adapt it to your own style and needs.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
// File: RadioDemo2.java - Demo radio buttons using convenience class.
// Author: Fred Swartz, 2009-01-02, Placed in public domain.

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

///////////////////////////////////////////////////////////////// RadioDemo2
class RadioDemo2 extends JFrame {

    //========================================================== constructor
    RadioDemo2() {
        //... Create the buttons.
        JRadioButton yesButton   = new JRadioButton("Yes", true);
        JRadioButton noButton    = new JRadioButton("No");
        JRadioButton maybeButton = new JRadioButton("Maybe");

        //... Use convenience class to group and layout buttons.
        EZRadioButtonPanel radioPanel = new EZRadioButtonPanel("Married?"
                                          , yesButton, noButton, maybeButton);

        //... Set window attributes.
        setContentPane(radioPanel);  // Button panel is only content.
        pack();                      // Layout window.
    }
    
    //================================================================= main
    public static void main(String[] args) {
        JFrame window = new RadioDemo2();
        window.setTitle("RadioDemo2");  // But window is too small to show it!
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLocationRelativeTo(null);  // Center window.
        window.setVisible(true);
    }
}
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
// File : EZRadioButtonPanel.java - Convenience class for radio buttons.
// Version: 2009-01-02
// Author : Fred Swartz, Placed in public domain.
// Enhancements: Could add more general borders and layouts, but I chose the
//               simplest thing that works for me.  Modify it as you wish.

import java.awt.*;
import javax.swing.*;

/** A conventience class to avoid the work of putting buttons in a
 * group and laying them out in a panel with a titled border.
 * @author Fred Swartz, placed in the public domain.
 */
public class EZRadioButtonPanel extends JPanel {
    //==================================================================== types
    private enum Orientation {_VERTICAL, _HORIZONTAL}
    
    //================================================================ constants
    public static final Orientation VERTICAL   = Orientation._VERTICAL;
    public static final Orientation HORIZONTAL = Orientation._HORIZONTAL;

    //=================================================================== fields
    //... The button group is saved only for clearSelection and reference it.
    private ButtonGroup _buttonGroup = new ButtonGroup();

    //============================================================== constructor
    /** This most common constructor creates a vertical layout of
     *  the radio buttons with an etched titled border (if title is non-null).
     * @param title   Text to use in the titled border.  No border if this is null.
     * @param buttons The radio buttons.
     */
    public EZRadioButtonPanel(String title, JRadioButton... buttons) {
        this(VERTICAL, title, buttons);
    }

    //============================================================== constructor
    /** This more general constructor allows specification of the orientation,
     * either horizontal or vertical.
     * @param orientation EZRadioButtonPanel.Orientation.VERTICAL or
     *                    EZRadioButtonPanel.Orientation.HORIZONTAL
     *                    (I could have used a "magic value", like
     *                     a true/false, 0/1, ... but the extra typing
     *                     may be worth it because the meaning will be clear.)
     *
     * @param title   Text to use in the titled border.  No border if this is null.
     * @param buttons The radio buttons.
     */
    public EZRadioButtonPanel(Orientation orientation, String title, JRadioButton... buttons) {
        //... Create a button group.

        //... Selet layout.
        if (orientation == VERTICAL) {
            this.setLayout(new GridLayout(buttons.length, 1));
        } else {
            this.setLayout(new FlowLayout(FlowLayout.LEADING));
        }

        //... Add buttons to the button group and the layout.
        for (JRadioButton button : buttons) {
            _buttonGroup.add(button);
            this.add(button);
        }

        //... Add a border if required.
        if (title != null) {
            this.setBorder(BorderFactory.createTitledBorder(
                   BorderFactory.createEtchedBorder(), title));
        }
    }

    //=========================================================== clearSelection
    /** Makes all radio buttons in the group unselected. */
    public void clearSelection() {
        _buttonGroup.clearSelection();
    }
}