How to select multiple JCheckBoxe into ButtonGroup?

Samiey Mehdi picture Samiey Mehdi · Oct 8, 2013 · Viewed 11.3k times · Source

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.

Answer

Piotr M&#252;ller picture Piotr Müller · Oct 8, 2013

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.