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 (from the javax.swing.event package) 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.

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 MouseInputAdapter can help deal with the other common low-level event generator: the mouse. And last but not least, this section also covers the SwingPropertyChangeSupport class to show you a fast way of generating property change events.

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 collection, 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 ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.