Invetigation in Process 2: Event Pump DTs
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.
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.
We might introduce a doInBackgroundAndWait() method as below.
public class QEdtInvoker { ... public <T> T doInBackgroundAndWait(final Callable callable) throws Exception { final QEventPump eventPump = new QEventPump(); 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 QEventPump { protected JDialog dialog; public QEventPump(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.
The following demo displays an undecorated modal dialog which overlays our status bar (to appear to be our status bar) and displays a progress bar and a cancel button, while blocking our application.
(AddressFormDemo, 150k/500k, unsandboxed, Java6)
- Login or register to post comments
- Printer-friendly version
- evanx's blog
- 849 reads





