如何在Java中使用Button Group Swing控件?

时间:2010-02-20 05:05:46

标签: java swing netbeans radio-button

如何使用NetBeans将单选按钮添加到按钮组?

添加后,如何从按钮组中选择单选按钮?

6 个答案:

答案 0 :(得分:26)

  1. 从调色板中拖出ButtonGroup并将其放在GUI上。 它将显示在检查器面板中的其他组件下。
  2. 右键单击它并将变量名称更改为有意义的内容。
  3. 现在在GUI中选择一个单选按钮。
  4. 属性面板中,查找 buttonGroup 属性。
  5. 点击旁边的组合框,然后选择您的按钮组。

答案 1 :(得分:16)

我强烈建议您阅读this excellent tutorial。以下是文章中的代码摘录,它满足了关于如何为ButtonGroup创建和添加按钮的问题:

JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setSelected(true);

JRadioButton catButton = new JRadioButton(catString);

   //Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);

至于选择哪个项目,您基本上需要iterate through the items in the group calling isSelected

答案 2 :(得分:2)

要以编程方式选择单选按钮,请尝试以下操作:

private final ButtonGroup buttonGroup = new ButtonGroup();

JRadioButton btn01 = new JRadioButton("btn 1");
buttonGroup.add(btn01);
JRadioButton btn02 = new JRadioButton("btn 2");
buttonGroup.add(btn02);
JRadioButton btn03 = new JRadioButton("btn 3");
buttonGroup.add(btn03);
// gets the selected radio button
if(buttonGroup.getSelection().equals(btn01.getModel())) {
 // code
}

// similarly for the other radio buttons as well.

答案 3 :(得分:1)

How to Use Buttons, Check Boxes, and Radio Buttons

ButtonGroup group = new ButtonGroup();
group.add(new JRadioButton("one"));
group.add(new JRadioButton("two"));
//TO FIND SELECTED
//use a loop on group.getElements();
//and check isSelected() and add them
//to some sort of data structure

答案 4 :(得分:0)

在“导航器”窗格中的“其他组件”下,选择您的按钮组。然后在“属性”窗格中选择“代码”选项卡。选择省略号(...)以编辑“After-All-Set Code”部分。输入您的代码,将按钮添加到按钮组,如上所述。

例如:

attemptGroup.add(attemptRadio1); attemptGroup.add(attemptRadio2); attemptGroup.add(attemptRadio3);

答案 5 :(得分:0)

private final ButtonGroup agreeDisagree = new ButtonGroup();

    JToggleButton tglbtnAgree = new JToggleButton("Agree");
    tglbtnAgree.setSelected(true);
    tglbtnAgree.setBounds(227, 127, 75, 23);
    agreeDisagree.add(tglbtnAgree);
    contentPane.add(tglbtnAgree);

    JToggleButton tglbtnDisagree = newJToggleButton("Disagree");
    tglbtnDisagree.setBounds(307, 127, 75, 23);
    agreeDisagree.add(tglbtnDisagree);
    contentPane.add(tglbtnDisagree);