setSelected a specific jradiobutton in a buttongroup based on action command
Asked Answered
N

3

5

i want to setSelected a speicfic jradiobutton in a buttongroup based on the actionCommand(/name of the specific jradiobutton).

it could be done usind .setSelected(true)

for example,

JRadioButton rabbitButton = new JRadioButton("rabbit");
 rabbitButton .setActionCommand("rabbit");
JRadioButton pigButton = new JRadioButton("pig");
 pigButton .setActionCommand("pig");

ButtonGroup group = new ButtonGroup();

group.add(rabbitButton);
group.add(pigButton);

now.. without ,

{ rabbitButton.setSelected(true);} NOR {group.setSelected(rabbitButton.getModel,true)}

is there a way to setSelected(true) rabbitButton based on the action command()?

Niddering answered 16/1, 2012 at 4:8 Comment(2)
did you forget the homework tag :-)Nealah
@Nealah No! It's a management system for Old McDonald's farm!Bonnibelle
F
6
yourButtonGroup.clearSelection();
yourRadioButton.setSelected(true);
Freshet answered 13/7, 2014 at 21:10 Comment(0)
E
3

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(String rdValue, Enumeration elements ){
    while (elements.hasMoreElements()){
        AbstractButton button = (AbstractButton)elements.nextElement();
        if(button.getActionCommand().equals(rdValue)){
            button.setSelected(true);
        }
    }
}

then

setButtonGroup(yourValue, yourButtonGroup.getElements());
Enlace answered 10/9, 2016 at 11:40 Comment(0)
P
2

The ButtonGroup#getElements method gives you an enumeration of AbstractButton instances. The AbstractButton#getActionCommand allows you to retrieve the action command and the AbstractButton#getSelected allows you to alter the selection.

So there is a way, but you will have to loop over the enumeration yourself.

Psychokinesis answered 16/1, 2012 at 7:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.