问题描述
我有三个如下所示的JCheckBox:
I have three JCheckBox like following:
final JCheckBox c1 = new JCheckBox("A");
final JCheckBox c2 = new JCheckBox("B");
final JCheckBox c3 = new JCheckBox("C");
我通过ButtonGroup对此复选框进行了分组,如下所示:
I make a group by ButtonGroup for this checkboxes like following:
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.
推荐答案
ButtonGroup
的目的是多重排斥选择.仅当您要收集按钮集合时才不要创建ButtonGroup
.代替ButtonGroup
,使用像ArrayList
这样的标准集合.
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
.
List<JCheckBox> buttons = new ArrayList<>();
buttons.add(c1);
buttons.add(c2);
buttons.add(c3);
...
for ( JCheckbox checkbox : buttons ) {
if( checkbox.isSelected() )
{
SelectedItem += btn.getText() + ",";
}
}
更多注意事项:在Swing事件线程(invokelater
)中进行更新(.setText
),记住最好在这种级联中创建StringBuilder,但是使用这样的UI组件数量,对性能的影响可能不会明显
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.
这篇关于如何选择多个JCheckBoxe到ButtonGroup中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!