Skip to main content

Invetigation in Process 2: Event Pump DTs

Posted by evanx on November 22, 2006 at 2:40 AM PST

It is often convenient to execute long tasks synchronously, that is to say, to wait for the task to complete, so that we can then do something appropriate like update the GUI. In order for our GUI to remain responsive while our long task is executing, we can use foxtrot.sf.net which manages to hook into the EventDispatchThread.pumpEvents() method to keep the events rolling.

Salientology

In case you don't want to read "Event Pump DTs, a scifi space opera," in all its gory detail, we extract some salient bits and present them below.

Code Glance

We might introduce a doInBackgroundAndWait() method as below.

public class EdtInvoker {
    ...
    public T doInBackgroundAndWait(final Callable callable)
    throws Exception {
        final EventPump eventPump = new EventPump();
        SwingWorker worker = new SwingWorker() {
            protected Object doInBackground() throws Exception {
                try {
                    return callable.call();
                } finally {
                    eventPump.done();
                }
            }
        };
        worker.execute();
        eventPump.pumpEvents();
        try {
            return (T) worker.get();
        } catch (Exception e) {
            throw getActualCause(e);
        }
    }
}

An alternative to actually pumping events is to a use an "invisible" modal Dialog to disable and block our application while executing a "background" task (synchronously).

public class EventPump {
    protected JDialog dialog;
   
    public EventPump(JFrame frame) {       
        dialog = new JDialog(frame, true);
        dialog.setUndecorated(true);
        dialog.setBounds(0, 0, 0, 0);
    }
   
    public void pumpEvents() {
        dialog.setVisible(true);
      
    }
   
    public void done() {
       dialog.setVisible(false);
    }   
}

In this case we aren't actually pumping all events on our frame, but are disabling mouse and keyboard events by means of the modal dialog, which invokes the EDT's pumpEventsForHierachy() method.

Related Topics >>