Search code examples
javaswingevent-dispatch-threadinvokeandwait

Returning values from Swing using invokeAndWait


I've been using the following approach to create components and return values from Swing to/from outside the EDT. For instance, the following method could be an extension to JFrame, to create a JPanel and add it to the parent JFrame:

public JPanel threadSafeAddPanel() {

    final JPanel[] jPanel = new JPanel[1];

    try {
        EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                jPanel[0] = new JPanel();
                add(jPanel[0]);
            }
        });
    } catch (InterruptedException ex) {
    } catch (InvocationTargetException ex) {
    }

    return jPanel[0];
}

The local 1-length array is used to transfer the "result" from inside the Runnable, which is invoked in the EDT. Well, it looks "a bit" hacky, and so my questions:

  1. Does this make sense? Is anybody else doing something like this?
  2. Is the 1-length array a good way of transferring the result?
  3. Is there an easier way to do this?

Solution

    • Swallowing exceptions without even logging them: bad!! - you will hate yourself when you come upon something like that after a 2 hours bug-hunt
    • No, the array is not a good way; for one thing, it offers no easy method for the calling code to wait for the EDT thread to execute the Runnable before fetching the result
    • There's a class designed explicitly for this kind of thing: SwingWorker