Search code examples
javaswingswingworker

Java 5 SwingWorker replacement


Our Swing application performs some long-running tasks in a background thread using the excellent SwingWorker class. However, a lot of older Macs only support Java 5, so we want to compile our application as 5 instead of 6. Because SwingWorker was introduced in Java 6 we can no longer use it.

Would the following be an acceptable replacement if I only need to do something in the background and then communicate it in the GUI when done? Or am I forgetting something crucial?

public static void wannabeSwingWorker(final Runnable doInBackground, final Runnable callback) {
    Thread backgroundThread = new Thread(new Runnable() {
        public void run() {
            doInBackground.run();
            SwingUtilities.invokeLater(callback);
        }
    });
    backgroundThread.start();
}

Solution

  • I'll let someone else comment on the suitability of your code, but as an alternative you can download a backport of Swingworker for use in Java 5 here.