Event listener java
An event listener in Java is designed to process some kind of event it "listens" for an event, such as a user's mouse click or a key press, and then it responds accordingly. An event listener must be connected to an event object that defines the event. For example, graphical components like a JButton or JTextField are known asevent sources. This means that they can generate events (called event objects),such as providing a JButton for a user to click, or a JTextField in which a user can enter text. The event listener's job is to catch those events and do something with them. How Event Listeners WorkEach event listener interface includes at least one method used by the equivalent event source. For this discussion, let's consider a mouse event, i.e. anytime a user clicks something with a mouse, represented by the Java class MouseEvent. To handle this type of event, you would first create a MouseListener class that implements the Java MouseListener interface. This interface has five methods; implement the one that relates to the type of mouse action you anticipate your user taking. These are:
As you can see, each method has a single event object parameter: the particular mouse event it is designed to handle. In your MouseListener class, you register to "listen to" any of these events so that you are informed when they occur. When the event fires (for example, the user clicks the mouse, as per the mouseClicked() method above), a relevant MouseEvent object representing that event is created and passed to theMouseListener object registered to receive it. Types of Event ListenersEvent listeners are represented by different interfaces, each of which is designed to process an equivalent event. Note that event listeners are flexible in that a single listener can be registered to "listen" to multiple types of events. This means that, for a similar set of components that perform the same type of action, one event listener can handle all the events. Here are some of the most common types:
|