【问题标题】:Get All JRadioButton from a ButtonGroup从 ButtonGroup 中获取所有 JRadioButton
【发布时间】:2017-05-09 21:49:38
【问题描述】:
如果我们认为我有一个 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 Selected?
【问题讨论】:
标签:
java
swing
radio-button
buttongroup
【解决方案1】:
终于找到了解决办法,我觉得有办法返回Enumeration<AbstractButton>,所以用它来返回这个ButtonGroup的所有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);
}