MouseMotionListener vs MouseMotionAdapter

MouseMotionListener vs MouseMotionAdapter


we know earlier difference between a listener and adapter. Now let us learn specifically with MouseMotionListener and MouseMotionAdapter.

First let us discuss interms of API MouseMotionListener vs MouseMotionAdapter

Following are the signatures as defined in Java API.

1. public interface MouseMotionListener extends EventListener

2. public abstract class MouseMotionAdapter implements MouseMotionListener

MouseMotionListener is an interface and MouseMotionAdapter is an abstract class.

There exists 2 abstract methods in MouseMotionListener.

public abstract void mouseDragged(MouseEvent);
public abstract void mouseMoved(MouseEvent);

Observe, the MouseMotionAdapter implements MouseMotionListener. All the above 2 abstract methods of MouseMotionListener are overridden by MouseMotionAdapter.

When you implement MouseMotionListener you override all the 2 abstract methods. Infact, you may be interested in only one. Atleast empty body should be given for the other method. To overcome this problem of overriding all MouseMotionAdapter was introduced.

So, now instead of implementing MouseMotionListener, you extend MouseMotionAdapter. Override any one method you would like. This is the advantage of adapters over listeners.

MouseMotionAdapter makes event handling code easier and cleaner than MouseMotionListener. It is because you override any one you like. Not required both abstract methods.

MouseMotionListener is preferred only when you override both abstract methods. If not MouseMotionAdapter is the preferred choice.

Pass your comments and suggestions on this tutorial MouseMotionListener vs MouseMotionAdapter.

Leave a Reply

Your email address will not be published. Required fields are marked *