【发布时间】:2011-01-19 01:22:15
【问题描述】:
如何使用 NetBeans 将单选按钮添加到按钮组?
添加后,如何从按钮组中选择单选按钮?
【问题讨论】:
标签: java swing netbeans radio-button
如何使用 NetBeans 将单选按钮添加到按钮组?
添加后,如何从按钮组中选择单选按钮?
【问题讨论】:
标签: java swing netbeans radio-button
ButtonGroup 并将其放到您的GUI 上。
它将显示在 Inspector 面板的 Other Components 下。【讨论】:
我强烈推荐阅读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);
至于获取哪个item被选中,基本需要iterate through the items in the group calling isSelected。
【讨论】:
要以编程方式选择单选按钮,请尝试以下操作:
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.
【讨论】:
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
【讨论】:
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);
【讨论】:
在您的导航窗格中,在“其他组件”下,选择您的按钮组。然后在“属性”窗格中选择“代码”选项卡。选择省略号 (...) 以编辑“After-All-Set Code”部分。输入您的代码以将按钮添加到按钮组,如上所述。
例如:
attemptGroup.add(attemptRadio1);
attemptGroup.add(attemptRadio2);
attemptGroup.add(attemptRadio3);
【讨论】: