Global Event Dispatching
Posted by Rob Camick on September 6, 2009
As a user interacts with a GUI, by using the mouse or keyboard, Swing handles the interaction by dispatching events to the appropriate component for processing. In turn the component will notify any listeners that the event has been received and processed. There may be times when you want to intercept or alter the event before it is dispatched to the component. Swing provides a few different approaches that will allow you to control the dispatching of events.
The primary way Swing dispatches events is by using an EventQueue. The EventQueue is part of the functionality provided by the Toolkit class. We can easily create a custom EventQueue by overriding the dispatchEvent(…) method. This now gives us access to every event before it is dispatched to its final destination. A custom EventQueue is added to the Toolkit using code like the following:
EventQueue queue = new EventQueue()
protected void dispatchEvent(AWTEvent event)
To prevent an event from being dispatched, return without invoking super.dispatchEvent(…). This approach of intercepting events was used in my Disabled Panel solution.
Another more specialized dispatcher would be the KeyEventDispatcher. As the name implies this Interface can be used to control the dispatching of KeyEvents. Once the Interface is implemented you add the class to the KeyboardFocusManager as follows:
KeyEventDispatcher dispatcher = new KeyEventDispatcher()
public boolean dispatchKeyEvent(KeyEvent e)
In this case to prevent an event from being dispatched, the method should return true.
Both examples show the default behaviour of these classes by dispatching the event as it is received. The code to prevent events from being dispatched will obviously depend on your requirements. When customizing the behaviour remember that the code should be simple and efficient so you don’t impact the GUI response time.