How to count number of JCheckboxes checked?

后端 未结 4 1102
旧时难觅i
旧时难觅i 2020-12-21 07:26

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

4条回答
  •  忘掉有多难
    2020-12-21 08:13

    add "ActionPerformed" event listener for all of your checkboxes & call this method inside event handler method to get number of checked checkboxes:

    int countCheckedCheckBoxes(){
        Component[] cs = getRootPane().getComponents();
        int checkNums = 0;
        for(Component c : cs){
            if(c instanceof JCheckBox){
                if(((JCheckBox)c).isSelected()){
                    checkNums++;
                }
            }
        }
        return checkNums;
    }
    

    getRootPane should return your main panel which components are located on it.

提交回复
热议问题