Get All JRadioButton from a ButtonGroup

1.4k views Asked by At

If we consider i have a ButtonGroup component, which have two JRadioButton like this :

JRadioButton bButton = new JRadioButton("Boy");
JRadioButton gButton = new JRadioButton("Girl");
ButtonGroup group = new ButtonGroup();

bButton.setSelected(true);

group.add(bButton);
group.add(gButton);

How can I get all the JRadioButton components from the ButtonGroup ordered by the default order so I can set the first JRadioButton Selected?

1

There are 1 answers

0
Youcef LAIDANI On BEST ANSWER

Finally i found the solution, i think there are a way to return Enumeration<AbstractButton>, so use it to return all the JRadioButton of this ButtonGroup

//Convert Enumeration to a List
List<AbstractButton> listRadioButton = Collections.list(group.getElements());

//show the list of JRadioButton
for (AbstractButton button : listRadioButton) {
    System.out.println("Next element : " + ((JRadioButton) button).getText());
    System.out.println("Is selectd = " + button.isSelected());
}

//Set the first JRadioButton selected
if(listRadioButton.size() > 0){
    listRadioButton.get(0).setSelected(true);
}