Получить все JRadioButton из группы кнопок

Если учесть, что у меня есть компонент ButtonGroup, у которого есть два JRadioButton, например:

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

bButton.setSelected(true);

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

Как я могу получить все компоненты JRadioButton из ButtonGroup, упорядоченные по умолчанию, чтобы я мог установить первый JRadioButton Selected?


person YCF_L    schedule 24.12.2016    source источник


Ответы (1)


Наконец я нашел решение, я думаю, что есть способ вернуть Enumeration<AbstractButton>, поэтому используйте его, чтобы вернуть все JRadioButton этого 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);
}
person YCF_L    schedule 24.12.2016