Java Reference
In-Depth Information
An event listener. A listener of an event registers itself with the source of
the event. When an event occurs, the source of the event invokes a
method on the listener.
An interface. The interface contains the methods that the listener must
implement and that the source of the event invokes when the event occurs.
For example, when a user clicks a java.awt.Button, the Button generates a
java.awt.event.ActionEvent. The Button invokes the actionPerformed() method
on each registered listener of the Button, passing in the ActionEvent object. The
actionPerformed() method is defined in the java.awt.event.ActionListener
interface, which each listener must implement. In this scenario, the Button is
the source of the event, the interface is ActionListener, and the listener is any
class that implements ActionListener and registers itself with the Button.
Classroom Q & A
Q: How do you register a listener with a Button?
A: Two steps are involved. You first need to write a class that imple-
ments ActionListener. You then invoke the addActionListener()
method on the Button, passing in an instance of your class.
Q: So do all components generate an ActionEvent?
A: No. There are many types of events, and each event has a corre-
sponding listener interface. For example, windows generate
WindowEvent objects and invoke a method from the WindowLis-
tener interface. A check box generates an ItemEvent and invokes a
method in the ItemListener interface.
Q: How do you know what events a component generates?
A: Well, one of my main goals in this chapter is to show you how to
determine the events that a component generates. The simplest
way to tell is to look for methods in the component's class of the
form add<event_name>Listener(). For example, if a component
has an addMouseListener() method, the component generates a
MouseEvent.
Q: So what interface do you implement to listen to a MouseEvent?
A: Java components use a standard naming convention for events. If
the name of the event is MouseEvent, the name of the corre-
sponding interface is MouseListener, and the name of the method
you invoke to register a listener is addMouseListener().
Search WWH ::




Custom Search