我应该在 SwingWorker.doInBackground() 中使用 SwingUtilities.invokeLater() 吗? [英] Should i use SwingUtilities.invokeLater() inside of SwingWorker.doInBackground()?

查看:34
本文介绍了我应该在 SwingWorker.doInBackground() 中使用 SwingUtilities.invokeLater() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Swing Worker 与 EDT 交互的常用方法是使用 get() 方法.但我有一个很长的任务和这样的代码:

The common way to interact with EDT from swing worker is useing get() method. But i have a long task and code like this:

public Void doInBackground() {
    for(Object o : objects) {
         doSomething();
         MyGlobalGUIConsole.addMessage("Done for " + o);
    }
}

在大多数教程中建议使用返回值从 SwingWorker 返回到 EDT,但我可以:

In most tutotials is recommended to use return values to get something back from SwingWorker to EDT, but can i just:

public Void doInBackground() {
    for(Object o : objects) {
        doSomething();
        SwingUtilities.invokeLater(new Runnable() {        
            @Override                                      
            public void run() {                            
                MyGlobalGUIConsole.addMessage("Done for " + o);
            }                                              
        });                                                
    }
}

推荐答案

你可以,但是 SwingWorker 有一些方法可以报告后台任务的进度:你从 调用 publish()doInBackground() 以发布进度,您可以覆盖 process()(在 EDT 中调用)以显示进度.所以上面的代码可以改写为:

You can, but the SwingWorker has methods designed to report progress of a background task: you call publish() from doInBackground() to publish progress, and you override process() (which is called in the EDT) in order to display the progress. So the above code could be rewritten as:

public Void doInBackground() {
    for(Object o : objects) {
        doSomething();
        publish("Done for " + o);                           
    }                                             
}

@Override
protected void process(List<String> messages) {
    for (String message : messages) {
        MyGlobalGUIConsole.addMessage(message);
    }
}

这篇关于我应该在 SwingWorker.doInBackground() 中使用 SwingUtilities.invokeLater() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆