Java Reference
In-Depth Information
subclass maintains references to its registered listeners in the listenerList . For simplicity,
we've diagramed listenerList as an array below the JTextField object in Fig. 12.13.
textField1
handler
JTextField object
TextFieldHandler object
listenerList
public void actionPerformed(
ActionEvent event )
{
// event handled here
}
...
This reference is created by the statement
textField1.addActionListener( handler );
Fig. 12.13 | Event registration for JTextField textField1 .
When the following statement (line 43 of Fig. 12.9) executes
textField1.addActionListener(handler);
a new entry containing a reference to the TextFieldHandler object is placed in
textField1 's listenerList . Although not shown in the diagram, this new entry also in-
cludes the listener's type ( ActionListener ). Using this mechanism, each lightweight
Swing component maintains its own list of listeners that were registered to handle the com-
ponent's events .
Event-Handler Invocation
The event-listener type is important in answering the second question: How does the GUI
component know to call actionPerformed rather than another method? Every GUI com-
ponent supports several event types , including mouse events , key events and others. When
an event occurs, the event is dispatched only to the event listeners of the appropriate type.
Dispatching is simply the process by which the GUI component calls an event-handling
method on each of its listeners that are registered for the event type that occurred.
Each event type has one or more corresponding event-listener interfaces . For example,
ActionEvent s are handled by ActionListener s, MouseEvent s by MouseListener s and
MouseMotionListener s , and KeyEvent s by KeyListener s . When an event occurs, the GUI
component receives (from the JVM) a unique event ID specifying the event type. The GUI
component uses the event ID to decide the listener type to which the event should be dis-
patched and to decide which method to call on each listener object. For an ActionEvent , the
event is dispatched to every registered ActionListener 's actionPerformed method (the only
method in interface ActionListener ). For a MouseEvent , the event is dispatched to every
registered MouseListener or MouseMotionListener , depending on the mouse event that
 
Search WWH ::




Custom Search