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?
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.
You can add it to your checkbox with the addItemListener() method in the AbstractButton class. Just replace addChangeListener with this: