Get all selected checkboxes in Java

后端 未结 2 790
半阙折子戏
半阙折子戏 2021-01-13 08:50

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

相关标签:
2条回答
  • 2021-01-13 09:00
    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).

    0 讨论(0)
  • 2021-01-13 09:25

    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.

    0 讨论(0)
提交回复
热议问题