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.
From documentation:
Class 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
The purpose of
ButtonGroup
is multiple-exclusive selection. Do not createButtonGroup
only if you want to have a collection of your buttons. Instead ofButtonGroup
use a standard collection likeArrayList
.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.