Event Utilities

If you extend one of the Swing components to add functionality, or indeed, build your own component from scratch, you need to handle event listeners for any events you might generate. The EventListenerList class is designed to aid in that task. This class is similar in many ways to the AWTEventMulticaster; however, it supports any type of listener and assumes you’ll use only the appropriate listeners for a given event type. Unlike the AWT multicaster, it does not assume all of the listeners support the same events.

The KeyStroke class can also help handle keyboard events. Rather than listening to every key that gets pressed and throwing out the things you don’t care about, you can use the KeyStroke class to register specific actions with specific keys.

The EventListenerList Class

If your component generates events, it must contain methods to add and remove interested listeners. Following the JavaBeans design patterns, these are the add Type Listener() and remove Type Listener() methods. Typically you store the listeners in a vector, and then use the vector as a rollcall for who to send events to when the time comes. This is a very common task for components that generate events, and the EventListenerList can help lift some (but certainly not all) of the burden of coding the event firing.

The EventListenerList stores listeners as pairs of objects, one object to hold the listener’s type and one to hold the listener itself. At any time, you can retrieve all of the current ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.