Creating Radio Buttons with JRadioButton

In this tutorial, you will learn how to use JRadionButton class to create radio buttons.

Radio buttons allow user to make a single choice from a set of options. To create a radio button, you use JRadioButton class.

The radio buttons are often used in a group to display multiple options therefore they are used with ButtonGroup class. The ButtonGroup enfores only one button in a group is selected at a given time. The ButtonGroup does not have visual appearance. It is just used to hold a logical grouping sets of buttons.

Here are the most common used constructors of JRadioButton class:

JRadioButton ConstructorsMeaning
public JRadioButton( )Creates a radio button without text and icon. The state of radio buttonis not selected.
public JRadioButton(Icon icon)Creates a radio button with icon.
public JRadioButton(Icon icon, boolean selected)Creates a radio button with icon. The selection state of the radio button is indicated by the boolean parameter selected.
public JRadioButton(String text)Create a radio button with text.
public JRadioButton(String text, boolean selected)Create a radio button with text and initialize  the state of the radio button.
public JRadioButton(String text, Icon icon)Creates a radio button which displays both text and icon.
public JRadioButton(String text, Icon icon, boolean selected)Creates a radio button which displays both text and icon. The state of radio button can be initialized.

Like a checkbox, you can handle the state of a radio button using ActionListener or ItemListener.

Example of using JRadioButton and ButtonGroup

In this example, we will create three radio buttons and add them to a button group. When user selects a radio button, a message will popup to notify the button user clicks and state of selected radio button.

JRadioButton - Radio Button in Swing