Skip to main content

Gooey Event Hub

Posted by evanx on February 16, 2007 at 8:36 AM PST

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.

href="http://aptframework.dev.java.net/gooey/eventHub.html">
align="left" hspace="8"/>

style="text-decoration: none;">




Code Snippet

We create BackgroundEvent and UpdateGuiEvent classes to enable some EDT
switching as follows.

    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));
           }
        } ...
    }

where we wish to handle checkForNewMessagesAction in a background SwingWorker thread,
and once completed, switch back into the EDT to update the GUI.


Demo


Launch

  (EventHub, 150k/500k, unsandboxed, Java6)


style="text-decoration: none;">
style="text-decoration: none;">
style="text-decoration: none;">
Related Topics >>