从 ButtonGroup 获取所有 JRadioButton

Get All JRadioButton from a ButtonGroup

如果我们认为我有一个 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);

如何从按默认顺序排序的 ButtonGroup 中获取所有 JRadioButton 组件,以便我可以设置第一个 JRadioButton 选中?

终于找到解决办法了,我觉得有办法returnEnumeration<AbstractButton>,所以用它来return这个[=13]的所有JRadioButton =]

//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);
}