开发者

Java 5 SwingWorker replacement

开发者 https://www.devze.com 2023-01-23 06:52 出处:网络
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 com开发者_Python百科

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 com开发者_Python百科pile 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();
}


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.


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),


Take a look at Foxtrot, which works differently than most Swing concurrency libs.

Instead of firing a background thread to execute a long-running task, it emulates the approach taken by Swing when you show a modal dialog box by executing the long running task on the Swing EDT and firing up a new thread to handle GUI events.

When working with a long running task that returns a value that you immediately need to act on, this results in a very nice, procedural/non-concurrent looking piece of program code (exactly like checking the return value from JOptionPane.showConfirmDialog(...)).


If you don't have any issues with LGPL code in your product, you can use the backport version of SwingWorker to Java 5.

http://java.net/projects/swingworker

0

精彩评论

暂无评论...
验证码 换一张
取 消