Working With a Radio Button in Swing

Introduction

 
In this article, we are going to describe how to use a radio button in your application; you will learn how to create a Radio Button in the frame. The Java AWT top-level window is represented by the CheckBoxGroup.  A Java program provides you the CheckboxGroup. In this program, you will see how to create and show the Checkboxgroup component in the frame.
 
In this program, a radio button is created that is an item that can be selected or deselected and displays that state to the user. Here we are creating a group of buttons in which you can select only one option at a time. Here, the explanation for the procedure of inserting a checkbox group on the Java AWT frame.
 
For creating radio buttons you need some important steps.
 
Step 1 - Import the necessary package.
  1. import java.awt.*;  
  2. import java.awt.event.*;  
Step 2 - Create a frame and label and CheckBoxGroup.
  1. Frame fm=new Frame("RedioButton Group");  
  2.   
  3. Label la=new Label("What is your choice:");  
  4. CheckboxGroup cg1=new CheckboxGroup();  
Step 3 - Add the component to the frame.
  1. fm.add(la);  
  2. fm.add(new Checkbox("MCA", cg1, true));  
  3. fm.add(new Checkbox("B-tech", cg1, false));  
  4. fm.add(new Checkbox("MBA", cg1, false));  
  5. fm.add(new Checkbox("CA", cg1, false));  
  6. fm.setSize(250,200);  
  7. fm.setVisible(true);  
Step 4 - Create the listener class.
  1. fm.addWindowListener(new WindowAdapter() {  
  2.     public void windowClosing(WindowEvent we) {  
  3.         System.exit(0);  
  4.     }  
  5. });  
Step 5 - We create everything in the main method; now we close the main method and there is no need to create an object of my class.
Complete code 
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class MyRadioButton  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         Frame fm = new Frame("RedioButton DEMO");  
  8.         Label la = new Label("Slect your Degree:");  
  9.         fm.setLayout(new GridLayout(01));  
  10.         CheckboxGroup cg1 = new CheckboxGroup();  
  11.         fm.add(la);  
  12.         fm.add(new Checkbox("MATH", cg1, true));  
  13.         fm.add(new Checkbox("PHYSICS", cg1, false));  
  14.         fm.add(new Checkbox("CHEMISTRY", cg1, false));  
  15.         fm.add(new Checkbox("ENGLISH", cg1, false));  
  16.         fm.setSize(250200);  
  17.         fm.setVisible(true);  
  18.         fm.addWindowListener(new WindowAdapter()  
  19.             {  
  20.                 public void windowClosing(WindowEvent we)  
  21.                 {  
  22.                     System.exit(0);  
  23.                 }  
  24.             });  
  25.     }  
  26. }  
OUTPUT
 
Radiocmd.jpg
 
Radiobutton.jpg 
 
Resources