MouseListener vs MouseAdapter
We know earlier the difference between a listener and adapter. Let us learn now MouseListener vs MouseAdapter.
First let us discuss interms of API.
Following are the signatures as defined in Java API.
1. public interface MouseListener extends EventListener
2. public abstract class MouseAdapter implements MouseListener, MouseWheelListener, MouseMotionListener
MouseListener is an interface and MouseAdapter is an abstract class.
There exists 5 abstract methods in MouseListener.
public abstract void mouseClicked(MouseEvent);
public abstract void mousePressed(MouseEvent);
public abstract void mouseReleased(MouseEvent);
public abstract void mouseEntered(MouseEvent);
public abstract void mouseExited(MouseEvent);
Observe, the MouseAdapter implements MouseListener. All the above 5 abstract methods of MouseListener are overridden by MouseAdapter.
Implementing MouseListener to catch mouse events requires to override all the 5 abstract methods. Infact, you may be interested only in one or two. Atleast empty body should be given for the remaining methods. To overcome this problem of overriding all MouseAdapter was introduced.
So, now instead of implementing MouseListener, you extend MouseAdapter and override any one or two methods you would like. This is the advantage of adapters over listeners.
Now, MouseAdapter makes event handling code easier and cleaner than MouseListener because you override any one you would like instead of 5 abstract methods.
MouseListener is preferred only when you override all abstract methods, else, MouseAdapter is the preferred choice.
Pass your comments and suggestions on this tutorial MouseListener vs MouseAdapter.