How to count number of JCheckboxes checked?

java, jcheckbox, jframe, swing

Solution

One way: put all of the JCheckBoxes in an array or `ArrayList<JCheckBox>` and when desired, simply iterate through the list to see which check boxes are selected.

Another possible solution: if you have a tabular structure, use a JTable that holds Booleans in its model, then when desired iterate through the rows of the TableModel to see which rows hold Boolean.TRUE values.

Problem

I have 11 different checkboxes in my JFrame and want to be able to get a number whenever one is checked for how many total are checked. I know how to set up an ItemListener and see if one is checked, but I am not sure how I could check all of them.. EDIT: cblist is an ArrayList containing 11 JCheckBoxes. I gave every JCheckBox an item listener and hereis the class used when the checkboxes are clicked... ``` private class CheckClass implements ItemListener{ public void itemStateChanged(ItemEvent event){ for(cblist.isChecked){ ingnum++; } } } ``` In the for loop, how do I test all elements of the ArrayList..I understand my syntax is not correct right now.

Original source

Related problems