Java Reference
In-Depth Information
keyTextComponent.addActionListener(actionListener);
frame.add(keyTextComponent, BorderLayout.CENTER);
frame.add(textField, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
EventListenerList Class
Although the AWTEventMulticaster class is easy to use, it doesn't work for managing lists of
custom event listeners or any of the Swing event listeners found in javax.swing.event . You
could create a custom extension of the class for each type of event listener list you need to
manage (not practical), or you could just store the list in a data structure such as a Vector or
LinkedList . Although using a Vector or LinkedList works satisfactorily, when you use this method,
you need to worry about synchronization issues. If you don't program the list management
properly, the listener notification may happen with the wrong set of listeners.
To help simplify this situation, the Swing component library includes a special event-listener
support class, EventListenerList . One instance of the class can manage all the different types
of event listeners for a component. To demonstrate the class usage, let's see how the previous
example can be rewritten to use EventListenerList instead of AWTEventMulticaster . Note that
in this particular example, using the AWTEventMulticaster class is actually the simpler solution.
However, imagine a similar situation in which the event listener isn't one of the predefined
AWT event listeners or if you need to maintain multiple listener lists.
The adding and removing of listeners is similar to the technique used with the
AWTEventMulticaster in the previous example. You need to create a variable of the appropriate
type—this time EventListenerList —as well as define add and remove listener methods. One
key difference between the two approaches is that the initial EventListenerList is non- null ,
whereas the other starts off being null . A reference to an empty EventListenerList must be
created to start. This removes the need for several checks for a null list variable later. The adding
and removing of listeners is also slightly different. Because an EventListenerList can manage
a list of listeners of any type, when you add or remove the listener, you must provide the class
type for the listener being acted on.
EventListenerList actionListenerList = new EventListenerList();
public void addActionListener(ActionListener actionListener) {
actionListenerList.add(ActionListener.class, actionListener);
}
public void removeActionListener(ActionListener actionListener) {
actionListenerList.remove(ActionListener.class, actionListener);
}
Search WWH ::




Custom Search