In this lesson, you will learn.

JRadioButton is a component in Java Swing that represents a radio button, which is a round button that can be selected or deselected.
| Constructor | Description |
|---|---|
JRadioButton() |
Creates an unselected radio button with no text or icon. |
JRadioButton(String text) |
Creates an unselected radio button with the specified text. |
JRadioButton(String text, boolean selected) |
Creates a radio button with the specified text and selection state. |
JRadioButton(Icon icon) |
Creates an unselected radio button with the specified icon. |
JRadioButton(Icon icon, boolean selected) |
Creates a radio button with the specified icon and selection state. |
JRadioButton(String text, Icon icon) |
Creates a radio button with the specified text and icon. |
JRadioButton(String text, Icon icon, boolean selected) |
Creates a radio button with the specified text, icon, and selection state. |
package jradiobutton;
import javax.swing.*;
import java.awt.*;
public class JRadioButtonExample extends JFrame {
public JRadioButtonExample() {
// Set the frame properties
setTitle("JRadioButton Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Create radio buttons using different constructors
JRadioButton radioButton1 = new JRadioButton();
JRadioButton radioButton2 = new JRadioButton("Female");
JRadioButton radioButton3 = new JRadioButton("Other", true);
// Set text for the first radio button
radioButton1.setText("Male");
// Set the selection state of the second radio button
radioButton1.setSelected(true);
// Enable and disable some radio buttons
radioButton3.setEnabled(false);
// Add radio buttons to the frame
add(radioButton1);
add(radioButton2);
add(radioButton3);
//Make frame visible
setVisible(true);
}
public static void main(String[] args) {
// Create and display the frame
new JRadioButtonExample();
}
}

| Method | Description |
|---|---|
void setSelected(boolean b) |
Sets the selection state of the radio button. |
boolean isSelected() |
Returns the selection state of the radio button. |
void setText(String text) |
Sets the text of the radio button. |
String getText() |
Returns the text of the radio button. |
void setIcon(Icon icon) |
Sets the icon of the radio button. |
Icon getIcon() |
Returns the icon of the radio button. |
void setEnabled(boolean b) |
Enables or disables the radio button. |
boolean isEnabled() |
Checks if the radio button is enabled. |
void setMnemonic(int mnemonic) |
Sets the keyboard mnemonic for the radio button. |
int getMnemonic() |
Returns the keyboard mnemonic for the radio button. |
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.