在Java Swing中,可以使用ButtonGroup类来保存和管理单选按钮组。下面是一个保存单选按钮组的示例代码:
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class RadioButtonGroupExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Radio Button Group Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
JRadioButton radioButton3 = new JRadioButton("Option 3");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
buttonGroup.add(radioButton3);
frame.add(radioButton1);
frame.add(radioButton2);
frame.add(radioButton3);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
在上面的示例中,我们创建了三个单选按钮,并使用ButtonGroup类将它们组合在一起。然后,通过调用add()
方法将单选按钮添加到ButtonGroup中。最后,将单选按钮添加到JFrame中显示出来。注意,为了使单选按钮组可见,需要设置合适的布局管理器以及设置适当的JFrame大小。
这样,当用户在单选按钮组中选择一个选项时,只能选择其中一个选项,其他选项会自动取消选择。通过使用ButtonGroup类,可以方便地管理和获取选中的单选按钮。
上一篇:保存当前日期时间格式的屏幕截图。