How to count number of JCheckboxes checked?

后端 未结 4 1094
旧时难觅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 07:51

    you can keep a global counter countChecked and make the frame implements ItemListener

    for all the JCheckBox in your frame chkBox.addItemListener(this) and handle the events

    public class MyFrame extends JFrame implements ItemListener{
    
    private int countChecked = 0;
    private JPanel contentPane;
        public MyFrame() {
        contentPane = new JPanel();
        setContentPane(contentPane);
        JCheckBox chckbx = new JCheckBox("New check box");
        contentPane.add(chckbx, BorderLayout.CENTER);
        chckbx.addItemListener(this);
    }
    
    @Override
    public void itemStateChanged(ItemEvent ie) {
        if(ie.getSource().getClass() == JCheckBox.class)
        {
            if(ie.getStateChange() == ie.SELECTED)
                countChecked++;
            else if(ie.getStateChange() == ie.DESELECTED)
                countChecked--;
        }
    
    } 
    }
    

提交回复
热议问题