我如何等待SwingWorker的doInBackground()方法? [英] How do I wait for a SwingWorker's doInBackground() method?

查看:110
本文介绍了我如何等待SwingWorker的doInBackground()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下代码:

import java.lang.InterruptedException;
import javax.swing.SwingWorker;

public class Test
{
    private JDialog window;

    public Test
    {
        // instantiate window
    }

    private class Task extends SwingWorker<Void, Void>
    {
        public Void doInBackground()
        {
            try { Thread.currentThread().sleep(5000); }
            catch(InterruptedException e) {}
            return null;
        }
    }

    public void doTask()
    {
        Task task = new Task();
        task.execute();
    }

    protected void process()
    {
        // update various GUI components here
    }

    public static void main(String args[])
    {
        Test t = new Test();
        t.doTask();
        System.out.println("done");
    }
}

我需要等到 t.doTask()在打印出'done'之前完成,但我不确定如何。我知道我应该在这里使用 join(),但我需要一个线程来调用它,我不知道如何获得 doInBackground ()我需要调用的线程 join()。感谢您的帮助。

I need to wait until t.doTask() is done before printing out 'done', but I'm not sure exactly how. I know I should probably use join() here, but I need a thread to call it on, and I don't know how to get doInBackground()'s thread from where I need to call join(). Thanks for any help.

编辑:感谢您的回复。不幸的是, get()之类的东西并没有完全解决问题。在我的实际代码中,SwingWorker还有一个重写的 process()函数,该函数在后台线程运行时更新GUI窗口。 get() doInBackground 之后打印停止'完成',但GUI不会更新。我更新了我的示例代码以反映这一点,虽然现在它当然不会编译。

Thanks for the responses. Unfortunately, get() and the like don't quite solve the problem. In my actual code, the SwingWorker also has an overridden process() function that updates a GUI window while the background thread is running. get() does stop 'done' from being printed till after doInBackground, but then the GUI doesn't update. I updated my sample code to reflect this, although now of course it won't compile.

有没有办法让'完成'只打印一次 doInBackground 结束? GUI更新代码和'done'语句是否在同一个线程上?我需要创建一个新线程吗?

Is there a way to get 'done' to print only once doInBackground is finished? Are the GUI update code and the 'done' statement on the same thread? Do I need to make a new thread?

推荐答案

通常需要在 SwingWorker之后完成的任何事情完成后台工作是通过覆盖 done()方法完成的。完成后在Swing事件线程上调用此方法,允许您更新GUI或打印出一些内容或其他内容。如果你确实需要阻止它完成,你可以调用 get()

Typically anything that needs to be done after a SwingWorker completes its background work is done by overriding the done() method in it. This method is called on the Swing event thread after completion, allowing you to update the GUI or print something out or whatever. If you really do need to block until it completes, you can call get().

NB。在 done()方法中调用 get()将立即返回您的结果,因此您不必担心阻止任何UI工作。

NB. Calling get() within the done() method will return with your result immediately, so you don't have to worry about that blocking any UI work.

这篇关于我如何等待SwingWorker的doInBackground()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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