防止 Swing GUI 在后台任务期间锁定 [英] Prevent Swing GUI locking up during a background task

查看:35
本文介绍了防止 Swing GUI 在后台任务期间锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储对象列表的 Swing 应用程序.当用户点击按钮时,

I have a swing application which stores a list of objects. When the users clicks a button,

我想对列表中的每个对象执行两个操作,然后在完成后将结果绘制在 JPanel 中.我一直在尝试 SwingWorker、Callable &Runnable 进行处理,但无论我做什么,在处理列表时(可能需要几分钟,因为它受 IO 限制),GUI 被锁定.

I want to perform two operations on each object in the list, and then once that is complete, graph the results in a JPanel. I've been trying SwingWorker, Callable & Runnable to do the processing, but no matter what I do, while processing the list (which can take up to a few minutes, as it is IO bound), the GUI is locked up.

我有一种感觉,这可能是我调用线程的方式或其他方式,或者可能与图形功能有关?这不是线程,因为它非常快.

I have a feeling it's probably the way I'm calling the threads or something, or could it be to do with the graphing function? That isn't threaded as it is very quick.

我也必须按顺序执行两个处理阶段,那么确保第二个处理阶段等待第一个处理阶段的最佳方法是什么?我用过 join(),然后

I have to do the two processing stages in order too, so what is the best way to ensure the second one has waited on the first? I've used join(), and then

while(x.isAlive())  
{  
        Thread.sleep(1000);  
}

尝试确保这一点,但我担心这也可能是我的问题的原因.

to try and ensure this, but I'm worried this could be the cause of my problem too.

我一直在到处寻找一些指示,但由于找不到任何指示,我确定我在这里做了一些愚蠢的事情.

I've been looking everywhere for some pointers, but since I can't find any I'm sure I'm doing something stupid here.

推荐答案

问题是,您长时间运行的任务阻塞了保持 GUI 响应的线程.

The problem is, your long running task is blocking the Thread that keeps the GUI responsive.

您需要做的是将长时间运行的任务放在另一个线程上.

What you will need to do is put the long running task on another thread.

执行此操作的一些常见方法是使用计时器或 SwingWorker.

Some common ways of doing this are using Timers or a SwingWorker.

Java 教程在他们的并发课程.

为了确保第一个任务在第二个任务之前完成,只需将它们放在同一个线程上.这样您就不必担心让两个不同的线程正确计时.

To make sure the first task finishes before the second, just put them both on the same thread. That way you won't have to worry about keeping two different threads timed correctly.

以下是 SwingWorker 的示例实现:

Here is a sample implementation of a SwingWorkerFor your case:

public class YourTaskSwingWorkerSwingWorker extends SwingWorker<List<Object>, Void> {
    private List<Object> list
    public YourClassSwingWorker(List<Object> theOriginalList){
        list = theOriginalList;
    }

    @Override
    public List<Object> doInBackground() {
        // Do the first opperation on the list
        // Do the second opperation on the list

        return list;
    }

    @Override
    public void done() {
        // Update the GUI with the updated list.
    }
}

要使用此代码,当修改列表的事件被触发时,创建一个新的 SwingWorker 并告诉它启动.

To use this code, when the event to modify the list is fired, create a new SwingWorker and tell it to start.

这篇关于防止 Swing GUI 在后台任务期间锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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