簡體   English   中英

從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

最后,我找到了解決方案,我認為有一種方法可以返回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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM