Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all selected checkboxes in Java

I have a dialog in Java that presents ~ 15 checkboxes to the user. Is there a way to get the names of all the checked checkboxes at once? Currently, I'm looking one by one if they are selected, which isn't that fancy of a solution.

I'm looking for something similar to Getting all selected checkboxes in an array but then in Java

like image 573
Freek8 Avatar asked Jan 19 '12 17:01

Freek8


2 Answers

When you are adding your Checkboxes to your dialog also keep a reference in a Collection of some sort. Then when you want to see which are checked you can just Iterate over the collection and check the state of each of them. You can get the name by calling getText on it.

like image 62
DaveJohnston Avatar answered Nov 12 '22 00:11

DaveJohnston


List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
for( Component comp : panel.getComponents() ) {
   if( comp instanceof JCheckBox) checkboxes.add( (JCheckBox)comp );
}

This assumes all of the JCheckBox instances are a direct child of the container panel. If not then you'd need to recursively visit all the containers of panel using the same logic. Now, while you can do this it's typically better to save these references as you created them into a list. Then you can easily iterate over all of the checkboxes without having to do this code above. If you have embedded components it's better to ask the embedded component to perform whatever operation you want over the checkboxes it owns (as opposed to pulling them out of the component through a getter so you can mess them in some way).

like image 7
chubbsondubs Avatar answered Nov 12 '22 00:11

chubbsondubs