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.

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

JRadioButton


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

ConstructorDescription
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

// JRadioButtonDemo.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");
           bg.add(r1);
           panel.add(r1);
           r2 = new JRadioButton("Apple");
           bg.add(r2);
           panel.add(r2);
           r3 = new JRadioButton("Orange");
           bg.add(r3);
           panel.add(r3);
           r4 = new JRadioButton("Others");
           bg.add(r4);
           panel.add(r4);
           r1.setSelected(true);
           frame.add(panel);
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(280, 150);
           frame.setVisible(true);
      }
}


Output:

jradiobutton