JCheckbox change listener gets notified of mouse over events
checkbox, event-handling, events, java, listener
Solution
You get events on mouse over as focus gained/lost represents a change to the state of the component.
Instead you could use an ItemListener which will give you ItemEvents.
The object that implements the ItemListener interface gets this ItemEvent when the event occurs. The listener is spared the details of processing individual mouse movements and mouse clicks, and can instead process a "meaningful" (semantic) event like "item selected" or "item deselected".
You can add it to your checkbox with the addItemListener() method in the AbstractButton class. Just replace addChangeListener with this:
c.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.err.println(e.getStateChange());
}
});
Problem
Can some one please explain to me why this piece of code prints out to the console when you move your mouse over the check box? What is the "change" event that takes place? ``` import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Test { public static void main(String[] args) { JFrame f = new JFrame(); JCheckBox c = new JCheckBox("Print HELLO"); c.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { System.out.println("HELLO"); } }); f.getContentPane().add(c); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); } } ``` NOTE: I don't use an action listener because in my program i want to be able to do : ``` checkBox.setSelected(boolean) ``` and have my listener notified, which can't be done with an action listener. So is there a way to disable this "mouse over" event or another way i can implement my listener?