Java 如何选择多个 JCheckBoxe 到 ButtonGroup 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19245510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select multiple JCheckBoxe into ButtonGroup?
提问by Samiey Mehdi
I have three JCheckBox like following:
我有三个 JCheckBox,如下所示:
final JCheckBox c1 = new JCheckBox("A");
final JCheckBox c2 = new JCheckBox("B");
final JCheckBox c3 = new JCheckBox("C");
I make a group by ButtonGroup for this checkboxes like following:
我按 ButtonGroup 为此复选框创建一个组,如下所示:
final ButtonGroup bg = new ButtonGroup();
bg.add(c1);
bg.add(c2);
bg.add(c3);
I have a Button to display selected items into a label like following:
我有一个按钮可以将所选项目显示到标签中,如下所示:
String SelectedItem="";
Enumeration<AbstractButton> items= bg.getElements();
while (items.hasMoreElements()) {
AbstractButton btn = items.nextElement();
if(btn.isSelected())
{
SelectedItem+=btn.getText()+",";
}
}
lblA.setText(SelectedItem);
this work fine , but i cann't select multiple check boxes in run time.
这工作正常,但我无法在运行时选择多个复选框。
采纳答案by Piotr Müller
The purpose of ButtonGroup
is multiple-exclusive selection. Do not create ButtonGroup
only if you want to have a collection of your buttons. Instead of ButtonGroup
use a standard collection like ArrayList
.
的目的ButtonGroup
是多重排他选择。不要ButtonGroup
仅在您想要拥有一组按钮时才创建。而不是ButtonGroup
使用像ArrayList
.
List<JCheckBox> buttons = new ArrayList<>();
buttons.add(c1);
buttons.add(c2);
buttons.add(c3);
...
for ( JCheckbox checkbox : buttons ) {
if( checkbox.isSelected() )
{
SelectedItem += btn.getText() + ",";
}
}
Further notices: do updates (.setText
) in Swing event thread (invokelater
), remeber that it is better to create StringBuilder in such concatenation, but with UI component quantities like this, performance impact propably will be not noticeable.
进一步注意:.setText
在 Swing 事件线程 ( invokelater
) 中执行更新 ( ) ,请记住,最好在这种串联中创建 StringBuilder,但是对于这样的 UI 组件数量,性能影响可能不会很明显。
回答by EProgrammerNotFound
From documentation:
从文档:
Class ButtonGroup
ButtonGroup 类
This class is used to create a multiple-exclusion scope for a set of buttons.Creating a set of buttons with the same ButtonGroup object means that turning "on" one of those buttons turns off all other buttons in the group.
此类用于为一组按钮创建多排除范围。创建一组具有相同 ButtonGroup 对象的按钮 意味着“打开”这些按钮中的一个会关闭该组中的所有其他按钮。
That said, you probably are using the wrong class to do what you need, if you want to GROUP those checkboxes, put them in a panel, than you can work visibility, position and all other attributes with the panel instead of each checkbox.
也就是说,您可能正在使用错误的类来执行您需要的操作,如果您想对这些复选框进行分组,将它们放在一个面板中,那么您可以使用面板而不是每个复选框来处理可见性、位置和所有其他属性。
Here is the link to documentation: Link
这是文档的链接:链接