Reputation: 8369
I am getting confused how the MouseMotionListener is used behind the scenes
For example this is what i think interfaces do
Interface A {
method work();
}
class ConcreteA {
method work(){ //implementation goes here }
}
then a client code can call to any class that implements the A interface and call its work method
classImplementingA.work()
But here we implement the MouseMotionListener and add our own defition to the methods it exposes MouseDragged, mouseMoved.
So i want to know
Does internally java calls this interface methods in turn calling our defined methods OR something else
i.e java internal works like client code for this interface and we defined the behind the scene implementation.
So plz somebody show me how java is handling the mouse movements and making this interface work with it in an easy way.
Upvotes: 0
Views: 192
Reputation: 691715
Listeners in general are based on the observable/observer pattern.
Let's take a simpler example: ActionListener
. You want to "observe" a button. You are thus the observer, and the button is the observable. You create an instance of ActionListener
, and thus override its actionPerformed
method. You then add this listener to the button. And now, the button, each time it's clicked, will call back (notify) the listener by calling its actionPerformed
method.
A MouseMotionListener
uses the same principle: you create an instance of MouseMotionListener
and add it to a Swing component. Then, each time the mouse is moved inside this component, the component calls back (notifies) the listener by calling one of its methods (mouseDragged
or mouseMoved
, depending on whether a mouse button is pressed or not).
So, yes, you're right. The client of the interface, in this case, is not your own code, but the Swing components. They are the callers of the interface implementations you define.
Upvotes: 3