如何 select 来自 ButtonGroup 的 JRadioButton?

How to select a JRadioButton from ButtonGroup?

我尝试在 java 中做一个图像创建程序(使用 squares/circles/etc) 我在 ButtonGroup 中有几个 JRadioButtons,它们象征着我的程序的 "mode"(如果我画一个圆,我移动对象的东西 else/if)。 当我点击不同的模式时,"mode" 发生变化,我可以做我想做的事。 我的问题是当我尝试通过双击一个对象来更改模式时。我在 MouseListener 中进行。我可以 select 对象,更改 "mode",但我无法更改 ButtonGroup 上的 selected JRadio Button。 我搜索了一段时间(因为 setSelected() 不工作)。我知道 ButtonGroup 一次只能有一个按钮 selected。我怎么能deselect当前的和select我需要的(第一个)。 感谢您的任何建议。

来自文档:

public void setSelected(boolean b)

Sets the state of the button. Note that this method does not trigger an actionEvent. Call doClick to perform a programatic action change.

这里提到使用:

radioBtn.doClick();

我创建了一个小方法,允许我设置任何单选组按钮。如果您不想将 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);
        }
    }
}

然后

setButtonGroup(yourValue, yourButtonGroup.getElements());