Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between MouseListener and MouseAdapter in Java

I can't seem to understand the difference between the 2 interfaces. Why can't MouseAdapter be implemented like MouseListener and can only be extended? I'm fairly new to Java.

Considering we want to perform an action that can be completed with either of these 2 interfaces.

Also, when would it be wise to use the one and when the other ?

like image 909
Soutzikevich Avatar asked Dec 03 '22 22:12

Soutzikevich


2 Answers

I can't seem to understand the difference between the 2 interfaces. Why can't MouseAdapter be implemented like MouseListener and can only be extended

MouseAdapter implements MouseListener.

MouseAdapter:

An abstract adapter class for receiving mouse events. The methods in this class are empty. This class exists as convenience for creating listener objects. Extend this class to create a MouseEvent (including drag and motion events) or/and MouseWheelEvent listener and override the methods for the events of interest

In absence of MouseAdapter, if you implement MouseListener, you have to provide implementation to all of these interface methods.

mouseClicked(MouseEvent e)
mouseDragged(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mouseMoved(MouseEvent e)
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
mouseWheelMoved(MouseWheelEvent e)

when would it be wise to use the one and when the other ?

If you want to implement above 8 methods, implement MouseListener. If you want to provide implementation for only some of these 8 methods, use MouseAdapter and override only those methods of interest for you.

e.g. If you are interested only in implementing one event ( or few events) like mouseClicked(MouseEvent e) event, best to use MouseAdapter. If you implement MouseListener interface in this case, you have to provide blank implementation for other methods, which you are not going to implement.

like image 150
Ravindra babu Avatar answered Dec 06 '22 12:12

Ravindra babu


MouseListener is preferred only when you override all abstract methods else MouseAdapter is the preferred choice.

like image 37
Sapan Zaveri Avatar answered Dec 06 '22 12:12

Sapan Zaveri