How to select multiple JCheckBoxe into ButtonGroup

2019-09-03 02:48发布

问题:

I have three JCheckBox like following:

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:

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.

回答1:

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() + ",";
    }
}

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.



回答2:

From documentation:

Class 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.

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