Working With a Radio Button in Swing


Introduction

In this article we are going to descibe 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, explanation for the procedure of inserting checkbox group on the Java AWT frame.

For creating radio buttons you need some important steps.

Step 1: Import the necessary package.

import java.awt.*;

import java.awt.event.*;

Step 2 : Create a frame and label and CheckBoxGroup.

Frame fm=new Frame("RedioButton Group");

Label la=new Label("What is your choice:");
CheckboxGroup cg1=new CheckboxGroup();

Step 3 : Add the component to the frame.

fm.add(la);

fm.add(new Checkbox("MCA", cg1, true));

fm.add(new Checkbox("B-tech", cg1, false));

fm.add(new Checkbox("MBA", cg1, false));

fm.add(new Checkbox("CA", cg1, false));

fm.setSize(250,200);

fm.setVisible(true);

Step 4: Create the listener class.

fm.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

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
 

import java.awt.*;

import java.awt.event.*;

public class MyRadioButton

{

public static void main(String[] args)

{

Frame fm=new Frame("RedioButton DEMO");

Label la=new Label("Slect your Degree:");

fm.setLayout(new GridLayout(0, 1));

CheckboxGroup cg1=new CheckboxGroup();

fm.add(la);

fm.add(new Checkbox("MATH", cg1, true));

fm.add(new Checkbox("PHYSICS", cg1, false));

fm.add(new Checkbox("CHEMISTRY", cg1, false));

fm.add(new Checkbox("ENGLISH", cg1, false));

fm.setSize(250,200);

fm.setVisible(true);

fm.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent we)

{

System.exit(0);

}

});

}

}

OUTPUT

Radiocmd.jpg

Radiobutton.jpg


Resources


Using Radio Button in GridView

Select Single Radio Button in Gridview in Asp.Net
Working With JMenu in Swing
Radio Button Column in Datagrid in Silverlight 3
Cross browser conditional validation
 

Up Next
    Ebook Download
    View all
    Learn
    View all