在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會被取消選中。