5

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

Community
  • 1
  • 1
Freek8
  • 694
  • 4
  • 11
  • 24

2 Answers2

8

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.

DaveJohnston
  • 10,031
  • 10
  • 54
  • 83
7
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).

chubbsondubs
  • 37,646
  • 24
  • 106
  • 138
  • Alternatively, as you create the dialog, you could add the checkboxes to an `ArrayList`. That way they need not be direct children of the container panel. – user949300 Jan 19 '12 at 17:12
  • @user949300 Yes I described that exact method in the answer as well. – chubbsondubs Jan 19 '12 at 17:14
  • This seems like an even easier solution. However, i'm created the checkboxes with the visual editor in Netbeans, is there a way to add stuff to the code that Netbeans auto generates? – Freek8 Jan 19 '12 at 17:14
  • You can modify the code that Netbeans auto generates. Doing that might make it hard to use the visual editor again. I'm not too familiar with Netbeans visual editor to know how it works. If it creates a resource file, or gens code, is there an API to work with resource files it might generate. It's all unknown. – chubbsondubs Jan 19 '12 at 17:20