What I'm having trouble understanding is how exactly a method such as
public interface MouseListener extends EventListener {
public void mouseClicked(MouseEvent e) {
//code for what happens when you click the mouse on the component
}
}
knows the id of the mouse event. Why is the event only sent to the mouseClicked method when the event is performed? The constructors for these methods call for any of the possible mouse events so why is it only sent to the mouseClicked method when other methods have the same constructor (i.e. mousePressed, mouseReleased, etc.)
The Observer Pattern is the important thing to know.
This pattern is used to form relationships between objects at runtime.
The idea behind the pattern is simple - one of more Observers are interested in the state of a Subject and register their interest with the Subject by attaching themselves. When something changes in our Subject that the Observer may be interested in, a notify message is sent, which calls the update method in each Observer. When the Observer is no longer interested in the Subject's state, they can simply detatch themselves.
The whole idea of action listeners is based on this. Once you understand this pattern, it's straightforward.
When you register an ActionListener, it's the observer and the button is the subject. So when the button changes state, the actionPerformed method will be launched.
Note that all listeners are based on this pattern, when an event occurs, the registered ones will be notified about this event and will perform the actions. Swing, for example, manages all of the registering and event notification by itself (it's already "built in").
(http://java.dzone.com/articles/design-patterns-uncovered)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With