📅  最后修改于: 2023-12-03 15:01:32.549000             🧑  作者: Mango
JRadioButton is a Swing component which allows the user to choose one option from a group of options. It is a part of the javax.swing package and is typically used in forms, quizzes, and other similar applications where a user is required to make a choice from a set of options.
Below is an example of how to create a basic JRadioButton in Java:
import javax.swing.*;
import java.awt.*;
public class JRadioButtonExample extends JFrame {
private JRadioButton radioButton1;
private JRadioButton radioButton2;
private ButtonGroup radioGroup;
public JRadioButtonExample() {
// Set the frame properties
setTitle("JRadioButton Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the radio buttons and group
radioButton1 = new JRadioButton("Option 1");
radioButton2 = new JRadioButton("Option 2");
radioGroup = new ButtonGroup();
// Add the radio buttons to the group
radioGroup.add(radioButton1);
radioGroup.add(radioButton2);
// Add the radio buttons to the frame
setLayout(new GridLayout(3, 1));
add(new JLabel("Choose an option:"));
add(radioButton1);
add(radioButton2);
// Show the frame
setVisible(true);
}
public static void main(String[] args) {
JRadioButtonExample example = new JRadioButtonExample();
}
}
JRadioButton is a versatile Swing component that can be used to provide users with a visually intuitive way of making a choice between different options. It is easy to use and highly customizable, making it a popular choice for developers working on various types of applications.