Get all selected checkboxes in Java

限于喜欢 提交于 2020-01-11 05:35:11

问题


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


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/8930101/get-all-selected-checkboxes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!