Java Reference
In-Depth Information
«interface»
XListener
Trigger an event
User
Action
source: SourceClass
+add X Listener(listener: X Listener)
+ handler(event: XEvent)
(2) Register by invoking
source.add X Listener(listener);
(1) A listener object is an
instance of a listener interface
listener: ListenerClass
(a) A generic source object with a generic listener
«interface»
java.awt.event.ActionListener
source: javax.swing.JButton
+addActionListener(listener: ActionListener)
+ actionPerformed(event: ActionEvent)
(2) Register by invoking
source.add Action Listener(listener);
(1) An action event listener is an
instance of ActionListener
listener: CustomListenerClass
(b) A JButton source object with an ActionListener
F IGURE 16.5
A listener must be an instance of a listener interface and must be registered with a source object.
three columns in Table 16.1 list event types, the corresponding listener interfaces, and
the methods defined in the listener interfaces. The listener interface contains the
method(s), known as the event handler(s) , for processing the event. For example, as
shown in the first line of this table, the corresponding listener interface for
ActionEvent is ActionListener ; each listener for ActionEvent should imple-
ment the ActionListener interface; the ActionListener interface contains the
handler actionPerformed(ActionEvent) for processing an ActionEvent .
event handler
2. The listener object must be registered by the source object . Registration methods
depend on the event type. For ActionEvent , the method is addActionListener . In
general, the method is named addXListener for XEvent . A source object may fire
several types of events, and for each event the source object maintains a list of regis-
tered listeners and notifies them by invoking the handler of the listener object to
respond to the event, as shown in Figure 16.6. (Note that this figure shows the internal
implementation of a source class. You don't have to know how a source class such as
JButton is implemented in order to use it, but this knowledge will help you understand
the Java event-driven programming framework.)
register listener
source: SourceClass
source: javax.swing.JButton
+add X Listener( X Listener listener)
+add Action Listener( Action Listener listener)
An event is
triggered
An event is
triggered
Store in a list
Store in a list
event: X Event
event: Action Event
listener1
listener2
...
listener n
listener1
listener2
...
listener n
Invoke
listener1.handler(event)
listener2.handler(event)
...
listener n .handler(event)
Invoke
listener1.actionPerformed(event)
listener2.actionPerformed(event)
...
listener n .actionPerformed(event)
(b) Internal function of a JButton object
(a) Internal function of a generic source object
F IGURE 16.6
The source object notifies the listeners of the event by invoking the listener object's handler.
 
 
Search WWH ::




Custom Search