views:

720

answers:

2

Please check out this piece of code and tell me why on earth does it print 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?

+1  A: 

The state of the check box (even just the check box model) changes depending upon whether it has the mouse over it or not. So a state change event should be expected.

So, just check back to see what state the check box is in and update accordingly. It is better to go straight for the model, rather than using the "bloated" component interface.

Tom Hawtin - tackline
+2  A: 

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());
    }
});
Aaron
Thanks this works. I always though item listeners applied to list like components only. :)
Savvas Dalkitsis
No problem. It's actually ListSelectionListener that are used for lists. There is a different interface for lists and buttons because the list selections need to support selecting a range of cells which requires a different event type.
Aaron