Gooey Event Hub
We implement a event listener list singleton supporting weak references. Then we can add listeners to an object we wish to observe, and fire events to its observers, without implementing any such support in the observed objects eg. addListener(), removeListener(), fireEvent(). We can choose to fire an event in a background SwingWorker thread, or in the EDT eg. using invokeLater() or invokeAndWait(). So we might use this event hub as a basic event/message bus.
We create BackgroundEvent and UpdateGuiEvent classes to enable some EDT
switching as follows.
where we wish to handle checkForNewMessagesAction in a background SwingWorker thread,
and once completed, switch back into the EDT to update the GUI.
Code Snippet
public EventHubDemo() {
...
public void actionPerformed(ActionEvent event) {
if (checkForNewMessagesAction.equalsActionCommand(event)) {
checkForNewMessagesAction.setEnabled(false);
eventHub.fireEventInBackground(new BackgroundEvent(this, event));
} ...
}
protected void doInBackground(ActionEvent event, JProgressBar progressBar) {
if (checkForNewMessagesAction.equalsActionCommand(event)) {
try {
...
eventHub.fireEventAndWait(new UpdateGuiEvent(this, event));
} catch (Exception e) {
eventHub.fireEventAndWait(new ExceptionEvent(this, event, e));
}
} ...
}
Demo
(EventHub, 150k/500k, unsandboxed, Java6)





