Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 385
Kees Kist Avatar asked Nov 02 '10 10:11

Kees Kist


2 Answers

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.

like image 167
William Avatar answered Oct 01 '22 20:10

William


Your code should work correctly; of course you'll lose all the other features of SwingWorker (returning partial results and progress, being cancellable, supporting listeners),

like image 40
Michael Borgwardt Avatar answered Oct 01 '22 18:10

Michael Borgwardt