Create RadioButton in Java:
We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it. |
A RadioButton is a component that is either selected or deselected, similar to a CheckBox. The difference with RadioButton is that they are associated with a group, and only one radio button in the group can be selected. When a radio button in the group is selected, any other previously selected one in the group is deselected.
Java RadioButton Methods:
Methods | Description |
---|---|
String getText( ) | Returns the text for the RadioButton. |
boolean isSelected( ) | Returns whether or not the button is selected. |
void setBackground(Color) | Sets the background color. |
void setEnabled(boolean) | Enables (boolean is true) or disables (boolean is false) the RadioButton. |
void setFocusable(boolean) | Draws a box around the component if it has focus (boolean is true) or not if the boolean is false. |
void setOpaque(boolean) | Sets background as transparent (boolean is false) or solid (boolean is true). |
Sample Code to Create RadioButton in Java:


Output:
When you select the RadioButton of the corresponding color, it will display that color output in the console window.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Radiobtn extends JFrame implements ActionListener{
JRadioButton redButton;
JRadioButton blueButton;
JRadioButton blackButton;
Radiobtn()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
redButton = new JRadioButton("red");
blueButton = new JRadioButton("blue");
blackButton = new JRadioButton("black");
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(blueButton);
group.add(blackButton);
redButton.addActionListener(this);
blueButton.addActionListener(this);
blackButton.addActionListener(this);
this.add(redButton);
this.add(blueButton);
this.add(blackButton);
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==redButton) {
System.out.println("You have selected Red Color");
}else if (e.getSource()==blueButton) {
System.out.println("You have selected Blue Color");
} else if (e.getSource()==blackButton) {
System.out.println("You have selected Black Color");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Radiobtn();
}
}
Comments (No)