I am using Java.
How does an event source like a (button in a GUI) knows which method to call in an interface?
For example, I am listening to Mouse Events and have implemented a Mouse Listener interface in my class then how would the event source know whether it should call mousePressed()
, mouseReleased()
or some other abstract method in the in the interface?
I am aware that using addMouseListener(this)
, provides a way for the event source to call the method of an interface.
2
For the observable design pattern, see http://en.wikipedia.org/wiki/Observer_pattern
Roughly, when the user clicks the button of the mouse and your Java Application is active, the OS notifies the application (in this case, the JVM) about the click. Then the JVM creates the MouseEvent object, as well as other necessary objects for handling the event and searches for the listeners of that event (think that the Button object has a collection of MouseListener objects, and you added your listener to that collection). Then it iterates through all the listeners in that collection and calls the appropriate method. It knows what is the appropriate method because it’s defined in the MouseListener interface, thus it knows all objects in that collection implements the methods defined in the interface.
For example, suppose there’s this code in a Button class (it’s probably somewhere else, but it serves as an example):
// suppose mouseListenerCollection contains all the mouse listeners in the component
for(MouseListener listener : mouseListenerCollection){
listener.mouseClicked(event);
}
It invokes the mouseClicked(MouseEvent e) method because the mouse have been clicked and all objects that implements the MouseListener interface implements the mouseClicked method, and it’s specified that when a mouse is clicked, the mouseClicked method must be called.
For further information, always refer to the API javadoc.