0

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");
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
drake
  • 259
  • 4
  • 17

2 Answers2

3

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
        }
    }
});
BoDidely
  • 504
  • 3
  • 13
1

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.

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28
  • what are the dangers of overriding `actionPerformed`? If you implement the actionListener interface, you must implement the `actionPerformed` method. What does `super.actionPerformed` do in this case? – BoDidely Jul 15 '15 at 19:49
  • Most of the Swing components themselves implement various listener interfaces for their own internal use. That is why the `actionPerformed` exist in one of the super classes (I think `JToggleButton` in this case). By overriding it and not calling super that part of the functionality of the component is missed. The thumb rule is to use one of `add*Listener` methods and not override these type of methods from the super classes. – Dakshinamurthy Karra Jul 16 '15 at 04:15
  • so should I be calling super.itemStateChanged() in my answer? I don't quite understand the difference between implementing the interface at the class level and using it as the listener or giving each component its own listener with anonymous classes – BoDidely Jul 16 '15 at 13:26
  • @BoDidely: you are implementing an interface, so `super` call doesn't make any sense. I shall update my answer with more details a bit later. – Dakshinamurthy Karra Jul 17 '15 at 05:21