Get all selected checkboxes in Java

I have a dialog in Java that presents ~ 15 flags to the user. Is there a way to get the names of all checked flags at once? Currently, I look one by one if they are selected, which is not a whim of a decision.

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

+4
source share
2 answers

When you add your flags to your dialog, also save the link in a collection. Then, when you want to see which ones are checked, you can simply iterate over the collection and check the status of each of them. You can get the name by calling getText on it.

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

All JCheckBox instances are assumed to be direct children of the container panel. If not, you will need to recursively visit all panel containers using the same logic. Now, although you can do this, it’s usually best to keep these links when you create them in the list. Then you can easily iterate over all the checkboxes without having to do this code above. If you have built-in components, it is better to ask the embedded component to perform any operation that you need on the flags that it owns (as opposed to pulling them out of the component through the getter, so that you can somehow ruin them).

+5
source

Source: https://habr.com/ru/post/1391884/


All Articles