javaawtmouseeventmouse-listeners

How to listen to mouse movements and left button at the same time


What I want is this: when the mouse moves over cells (JPanels) and the left button is clicked (held down while moving the mouse), the cells should change state. Exactly what you would expect when drawing with the mouse on a canvas. This is what I do:

this.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent arg0) {
                if(SwingUtilities.isLeftMouseButton(arg0)) {
                    setItem(MapItems._W_);
                } else {
                    setItem(MapItems.___);
                }
                DrawableCell.this.repaint();
            }
        });

This doesn't work (nothing happens). Using mouseMoved() doesn't make a difference.

The only thing that does anything at all is:

public void mouseMoved(MouseEvent arg0) {
    if(arg0.isControlDown()) {
        setItem(MapItems._W_);
    } else {
        setItem(MapItems.___);
    }
    DrawableCell.this.repaint();
}
});

The problem with this is that since mouseMoved fires more than once, the state of the cell is changing rapidly with a random outcome.

How to do that?


Solution

  • You must use a mouseListener instead. See oracle docs for help.