Radio Buttons and JRadioButton AWT & Swing

Radio Buttons

Radio buttons provide a more user friendly environment for selecting only one option among many. It is a special kind of checkbox that is used to select only one option.  No button class is available in java.awt package. When we add checkbox to a checkbox group, they become radio button automatically.

Following methods are used to make a radio button.

getSelectedCheckbox()Determines which radiobox in group is currently selected.
setSelectedCheckbox()Used to set radiobox.


Radio buttons are supported by the JRadioButton class, which is concrete implementation of AbstractButton.

Declaration of JRadioButton Class

public class JRadioButton
      extends JTogglrButton
            implements Accessible

JRadioButton Constructors

JRadioButton()Creates an initially unselected radio button without any text.
JRadioButton(Icon icon)Creates an initially unselected radio button with specified the specified icon.
JRadioButton(Icon icon, boolean state)Creates an initially selected button with specified image.
JRadioButton(String str)Creates an unselected radio button with the specified text.
JRadioButton(String str, boolean state)Constructs a selected radio button with specified text.
JRadioButton(String str, Icon icon)Creates a radion button with specified string and specified image that is initially unselected.
JRadioButton(String str, Icon icon, boolean state)Creates a radio button that has specified text, image and selection state.

Example : Program to create radio button in Java


import javax.swing.*;
import java.awt.*;
public class JRadioButtonDemo
      public static void main(String args[])
           JRadioButton r1, r2, r3, r4;
           JFrame frame = new JFrame("JRadioButton Demo");
           JPanel panel = new JPanel();
           ButtonGroup bg = new ButtonGroup();
           r1 = new JRadioButton("Mango");
           r2 = new JRadioButton("Apple");
           r3 = new JRadioButton("Orange");
           r4 = new JRadioButton("Others");
           frame.setSize(280, 150);