简体   繁体   中英

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). 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. I'm able to select the object, to change the "mode", but I can't change the selected JRadio Button on my ButtonGroup. I searched for a while (since the setSelected() is not working). I know that ButtonGroup can have only a button selected at once. 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)

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

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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