java中如何管理两个JRadioButton,一次只能选择其中一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2253590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:16:18  来源:igfitidea点击:

How to manage two JRadioButtons in java so that only one of them can be selected at a time

javaswingjradiobutton

提问by stillStudent

How to manage two JRadioButtons in java so that only one of them can be selected at a time? Is there any method in java to take care of this or you need to build your own logic?

java中如何管理两个JRadioButton,一次只能选择其中一个?java中是否有任何方法可以解决这个问题,或者您需要构建自己的逻辑?

采纳答案by ccheneson

You have to add them in a ButtonGroup

您必须将它们添加到ButtonGroup 中

ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);

Ensure you add this code after the buttons are created using the new JRadioButtonconstructors, as appropriate.

确保在使用新JRadioButton构造函数创建按钮后添加此代码,视情况而定。

回答by uji

My java is rusty but if i remember correctly you have to use the ButtonGroup class. Add your radio buttons to ButtonGroup object. I think it will look like this.

我的 Java 生锈了,但如果我没记错的话,您必须使用 ButtonGroup 类。将您的单选按钮添加到 ButtonGroup 对象。我认为它看起来像这样。

ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(new JRadioButton('Label', false));
buttonGroup.add(new JRadioButton('Label2', true));

Hope this helps. I have abandoned Java years ago.

希望这可以帮助。几年前我已经放弃了 Java。