MouseAdapter methods - why `mouseDragged`, `mouseMoved` and `mouseWheelMoved` included?

Ernestas Gruodis picture Ernestas Gruodis · Aug 15, 2013 · Viewed 7.5k times · Source

My goal was to simplify this code (all works fine):

package test;

import java.awt.Window;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JWindow;

public class A extends JWindow implements MouseListener, MouseMotionListener {

    public A() {
        addMouseListener(A.this);
        addMouseMotionListener(A.this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }
}

But if I decide to use MouseAdapter like this:

addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        transferFocusBackward();
        //This method is being used, working fine
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, not working anymore
    }
});

mouseDragged receiving no events. But if I add MouseMotionListener like this:

addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }
});

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }
});

Then everything backs to normal. So my question is - what is the purpose of mouseDragged, mouseMoved and mouseWheelMoved methods in MouseAdapter class if they do not work?

Answer

Ernestas Gruodis picture Ernestas Gruodis · Aug 15, 2013

OK, I think I understand now: in MouseAdapter class documentation it is said that "Create a listener object using the extended class and then register it with a component using the component's addMouseListener, addMouseMotionListener, addMouseWheelListener methods". So now it looks like:

private class MouseListeners extends MouseAdapter {

    @Override
    public void mousePressed(MouseEvent e) {
        //This method is being used, working fine
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        //This method is being used, working fine
    }
}

and then:

MouseListeners listeners = new MouseListeners();   
addMouseListener(listeners);
addMouseMotionListener(listeners);

Now everything is OK.