Why are mouseDragged-events not received when using MouseAdapter?

Tim picture Tim · Apr 7, 2011 · Viewed 13.8k times · Source

Why are mouseDragged-events only received when using MouseMotionAdapter
and not when using MouseAdapter ?

Java has two abstract adapter classes for receiving mouse-events ;
MouseAdapter and MouseMotionAdapter.

Both classes have a mouseDragged(MouseEvent e)-method, but the
one in MouseAdapter does not seem to work ; mouseDragged-events
never get through with this one.

Both classes implement the MouseMotionListener-interface which
defines the mouseDragged-event, so I don't understand why it is
not working correctly on both of them.

Here is sample-code which shows this issue :

import java.awt.event.MouseAdapter;  
import java.awt.event.MouseEvent;  
import java.awt.event.MouseMotionAdapter;  
import javax.swing.JFrame;  

public class SwingApp extends JFrame
{
    public SwingApp()
    {   
        // No mouseDragged-event is received when using this : 
    this.addMouseListener(new mouseEventHandler()); 

    // This works correct (when uncommented, of course) :
    // this.addMouseMotionListener(new mouseMovedEventHandler());


    setBounds(400,200, 550,300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setVisible(true);
    }   

  public static void main(String args[])
  {
    new SwingApp();
  }

  class mouseEventHandler extends MouseAdapter
  {         
    @Override
    public void mouseDragged(MouseEvent e) // Why is this method never called ?
    {
        System.out.println(String.format("MouseDragged via MouseAdapter / X,Y : %s,%s ", e.getX(), e.getY()));
    }
  } 

  class mouseMovedEventHandler extends MouseMotionAdapter
  {           
    @Override
    public void mouseDragged(MouseEvent e)
    {
        System.out.println(String.format("MouseDragged via MouseMotionAdapter / X,Y : %s,%s ", e.getX(), e.getY()));
    }
  } 

}

Answer

aioobe picture aioobe · Apr 7, 2011

If you add it through

this.addMouseListener(new mouseEventHandler()); 

you will not receive motion related MouseEvents (That's not what you registered the listener for!)

You'll have to add the listener twice, i.e., add it using addMouseMotionListener as well:

mouseEventHandler handler = new mouseEventHandler();
this.addMouseListener(handler); 
this.addMouseMotionListener(handler);

in order to get both type of events.

(A side node, always use a capital first letter for your classes, i.e., use MouseEventHandler instead :-)