Java Reference
In-Depth Information
«interface»
java.util.EventListener
«interface»
ActionListener
«interface»
AdjustmentListener
«interface»
ComponentListener
«interface»
ContainerListener
«interface»
FocusListener
«interface»
ItemListener
«interface»
KeyListener
«interface»
MouseListener
«interface»
MouseMotionListener
«interface»
TextListener
«interface»
WindowListener
Fig. 12.12
|
Some common event-listener interfaces of package
java.awt.event
.
Each event-listener interface specifies one or more event-handling methods that
must
be declared in the class that implements the interface. Recall from Section 10.9 that any
class which implements an interface must declare
all
the
abstract
methods of that inter-
face; otherwise, the class is an
abstract
class and cannot be used to create objects.
When an event occurs, the GUI component with which the user interacted notifies
its
registered listeners
by calling each listener's appropriate
event-handling method
. For
example, when the user presses the
Enter
key in a
JTextField
, the registered listener's
actionPerformed
method is called. In the next section, we complete our discussion of
how the event handling works in the preceding example.
Let's illustrate how the event-handling mechanism works, using
textField1
from the ex-
ample of Fig. 12.9. We have two remaining open questions from Section 12.7:
1.
How did the
event handler
get
registered
?
2.
How does the GUI component know to call
actionPerformed
rather than some
other event-handling method?
The first question is answered by the event registration performed in lines 43-46 of
Fig. 12.9. Figure 12.13 diagrams
JTextField
variable
textField1
,
TextFieldHandler
variable
handler
and the objects to which they refer.
Registering Events
Every
JComponent
has an instance variable called
listenerList
that refers to an object of
class
EventListenerList
(package
javax.swing.event
). Each object of a
JComponent