Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JCheckbox change listener gets notified of mouse over events

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?

like image 330
Savvas Dalkitsis Avatar asked Aug 19 '09 21:08

Savvas Dalkitsis


3 Answers

Use c.setRolloverEnabled(false)` and you won't get any event for mouse motions.

like image 125
Fredrik Avatar answered Nov 08 '22 08:11

Fredrik


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());
    }
});
like image 32
Aaron Avatar answered Nov 08 '22 06:11

Aaron


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.

like image 21
Tom Hawtin - tackline Avatar answered Nov 08 '22 07:11

Tom Hawtin - tackline