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
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With