views:

298

answers:

3

In following code, mouseDragged is not recognized. What do I do wrong?

addMouseListener(new MouseInputAdapter() {

  @Override
  public void mouseDragged(MouseEvent e) { ... }
  @Override
  public void mousePressed(MouseEvent e) { ... }

});
+3  A: 
MouseInputAdapter mia = new MouseInputAdapter() {
  @Override
  public void mouseDragged(MouseEvent e) { ... }
  @Override
  public void mousePressed(MouseEvent e) { ... }
};
addMouseListener(mia);
addMouseMotionListener(mia); // <-- You're missing this one.
Nate
+2  A: 

It is not recognized because you are implementing mouseDragged inside of an addMouseListener.

mouseDragged is triggered by a MouseMotionListener and mousePressed is triggered by a MouseListener.

Therefore you need to implement both MouseListener and MouseMotionListener and add the right listener accordingly.

public class MyClass extends JPanel implements MouseListener,
                                               MouseMotionListener {

  public MyClass() {
    // whatever code you need, then add the listeners
    this.addMouseListener(this); 
    this.addMouseMotionListener(this);
   }

  public void mousePressed(MouseEvent e) { ... }
  public void mouseDragged(MouseEvent e) { ... }

}
Anthony Forloney
A: 

do not use addMouseListener, but addMouseMotionListener :

addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseMoved(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseDragged(MouseEvent e) {
            // TODO Auto-generated method stub

        }
    });

:D

Eko Kurniawan Khannedy
This I tried before I came here to ask, but it doesn't work, for the reasons mentioned by Anthony Forloney.