代码之家  ›  专栏  ›  技术社区  ›  Youcef LAIDANI

从按钮组获取所有JRadioButton

  •  3
  • Youcef LAIDANI  · 技术社区  · 8 年前

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

    我怎么才能得到所有的 单选框组件 来自 按钮组 按默认顺序排序,因此我可以设置第一个 单选框组件 挑选出来的?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Youcef LAIDANI    8 年前

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