简体   繁体   中英

How to unselect and undo with checkboxes using Java Swing?

I have a checkbox, when the checkbox is selected I want to add int 2 to my total. Then I want to be able to unselect it and then subtract int 2 to my total.

At the moment, I cant unselect and subtract 2.

Also, my checkbox is in a button group so I need to use clearSelection() as a solution to deselect.

The code I currently have for this is (which isn't work too well):

monTill4ChckBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if(monTill4ChckBox.isSelected()){

                mondayCost= mondayCost + 2; 
            }
            else{
            mondayCost= mondayCost - 2;             
            monAftergroup.clearSelection();
            }

I think you should add item listener to the checkbox for listening check state properly. Something like this;

monTill4ChckBox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) {
            if(monTill4ChckBox.isSelected()){
                mondayCost= mondayCost + 2; 
            }
            else{
                mondayCost= mondayCost - 2;             
                monAftergroup.clearSelection();
            }
            System.err.println("Counter: " + mondayCost);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM