简体   繁体   中英

Keeping Track of Every Time that a Checkbox is checked and unchecked

I have most of my java application done already, so I am now logging all user activity. One thing I want to keep track of is whenever one of my checkboxes is checked and unchecked. I am able to read at the end if the object is checked or unchecked, however I want to know each time the checkbox is used in real time. I want to know how many times the user checks and unchecks the box. Right now I am using something similar to this syntax, but it doesn't print a statement each time the checkbox is checked and unchecked.

public CheckboxAction(String text) {
    super(text);
}

@Override
public void actionPerformed(ActionEvent event) {
    JCheckBox cbLog = (JCheckBox) event.getSource();
    if (cbLog.isSelected()) {
        System.out.println("Logging is enabled");
    } else {
        System.out.println("Logging is disabled");
    }
}

An ItemListener seems appropriate here

yourJCheckBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0) {
        if (yourJCheckBox.isSelected()) {
            // Code to execute when it's selected
        }
        else {
            // Code to execute when not selected
        }
    }
});

First and foremost, do not override actionPerformed . If you need to - at least call super.actionPerformed before performing your action. Best way is to use addActionListener or in this case as @BoDidely mentioned use an addItemListener .

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