Create a JRadioButton Component in Java

In this section, you will learn how to create a radio
button in java swing. Radio Button is like check box. Differences between check
box and radio button are as follows:
- Check Boxes are separated from one to another where
Radio Buttons are the different-different button like check box from a same
ButtonGroup.
- You can checks multiple check boxes at once but this
can never done in the case of radio button. You can select only one radio
button at once from a group of the radio button.
- You can check or uncheck the check box but you can
on check the radio button by clicking it once.
Here, you will see the JRadioButton component creation
procedure in java with the help of this program. This example provides two radio
buttons same ButtonGroup. These radio buttons represent the option for choosing
male or female. Following is the image for the result of the given program:

The
creation of JRadioButton are completed by the following methods:
ButtonGroup:
This is the class of the javax.swing.*;
package, which is used to create a group of radio buttons from which you can
select only one option from that group of the radio buttons. This is class is
used by creating a instance of if using it's constructor. Radio Buttons are
added to the specified group using the add(JRadioButton) method of the ButtonGroup
class.
JRadioButton:
This is the class has been used to create a
single radio button for the application.
setSelected():
This method sets the value of the radio button.
This method takes a boolean value either true or false. If you
pass true value then the radio button will be selected otherwise the
radio button is not selected.
Here is the code of program:
import javax.swing.*;
import java.awt.*;
public class CreateRadioButton{
public static void main(String[] args) {
CreateRadioButton r = new CreateRadioButton();
}
public CreateRadioButton(){
JRadioButton Male,Female;
JFrame frame = new JFrame("Creating a JRadioButton Component");
JPanel panel = new JPanel();
ButtonGroup buttonGroup = new ButtonGroup();
Male = new JRadioButton("Male");
buttonGroup.add(Male);
panel.add(Male);
Female = new JRadioButton("Female");
buttonGroup.add(Female);
panel.add(Female);
Male.setSelected(true);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}
|
Download this example.

|