在Java中,单选框通常是通过使用JRadioButton类来实现的。可以按照以下步骤实现单选框功能:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
JFrame frame = new JFrame("Single Selection Example");
frame.setLayout(new FlowLayout());
JPanel panel = new JPanel();
frame.add(panel);
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
JRadioButton radioButton3 = new JRadioButton("Option 3");
ButtonGroup group = new ButtonGroup();
group.add(radioButton1);
group.add(radioButton2);
group.add(radioButton3);
panel.add(radioButton1);
panel.add(radioButton2);
panel.add(radioButton3);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
通过以上步骤,就可以实现一个简单的单选框功能。当用户点击其中一个JRadioButton时,只有该JRadioButton会被选中,其他的JRadioButton会被取消选中。