简体   繁体   English

如何从ButtonGroup中选择JRadioButton?

[英]How to select a JRadioButton from ButtonGroup?

I try to do an image creator program in java (with squares/circles/etc) I have a few JRadioButtons in a ButtonGroup that symbolizes my program's "mode" (if I draw a circle, something else/if I move the objects). 我尝试在java中创建一个图像创建程序(使用正方形/圆形/等)我在ButtonGroup中有一些JRadioButtons,它们象征着我的程序的“模式”(如果我画一个圆圈,其他东西/如果我移动对象)。 When I click on different modes, the "mode" changes and I'm able to do what I want. 当我点击不同模式时,“模式”会发生变化,我可以按照自己的意愿行事。 My problem is when I try to change the mode by double-clicking on an object. 我的问题是当我尝试通过双击对象来更改模式。 I do it in a MouseListener. 我是在MouseListener中完成的。 I'm able to select the object, to change the "mode", but I can't change the selected JRadio Button on my ButtonGroup. 我可以选择对象,更改“模式”,但我无法更改ButtonGroup上选定的JRadio按钮。 I searched for a while (since the setSelected() is not working). 我搜索了一会儿(因为setSelected()不起作用)。 I know that ButtonGroup can have only a button selected at once. 我知道ButtonGroup只能一次选择一个按钮。 How could I deselect the curent one and select the one I need (the first one). 我怎样才能取消选择一个并选择我需要的那个(第一个)。 Thank you for any advices. 谢谢你的任何建议。

From the docs: 来自文档:

public void setSelected(boolean b) public void setSelected(boolean b)

Sets the state of the button. 设置按钮的状态。 Note that this method does not trigger an actionEvent. 请注意,此方法不会触发actionEvent。 Call doClick to perform a programatic action change. 调用doClick以执行程序操作更改。

As mentioned here use: 如上所述,使用:

radioBtn.doClick();

I created a small method that allow me to set any radio group button. 我创建了一个小方法,允许我设置任何单选按钮组。 Very convenient if you don't want to use if for any radio button. 如果您不想使用if用于任何单选按钮,则非常方便。

public void setButtonGroup(int rdValue, Enumeration elements ){
    while (elements.hasMoreElements()){
        AbstractButton button = (AbstractButton)elements.nextElement();
        if(Integer.parseInt(button.getActionCommand())==rdValue){
            button.setSelected(true);
        }
    }
}

then 然后

setButtonGroup(yourValue, yourButtonGroup.getElements());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM