当GUI不更新信息时,通过SWING和多线程处理GUI [英] Handling GUI with SWING with multithreading when the GUI does not update informations

查看:112
本文介绍了当GUI不更新信息时,通过SWING和多线程处理GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个桌面应用程序是使用受 this启发的MVC模式设计的教程(但稍作修改).该应用程序需要做的是将文件列表从目录复制到另一个目录.我想做的基本上是在复制每个文件之后更新我的GUI.

So I have a desktop application designed using the MVC pattern inspired by this tutorial (but slightly modified). What this application needs to do is to copy a list of file from a directory to another. What I would like to do is basically update my GUI after every file is copied.

首先让我向您展示代码. 在我的模型中,我有这个虚拟方法(不是真正的方法,但背后的逻辑是相同的):

First of all let me show you the code. In my model I have this dummy method (not the real method but the logic behind it is the same):

public void dummyMethod(Integer k) throws InterruptedException{
    for(int i=0;i<10;i++){
        System.out.println(i);
    Thread.sleep(1000);
        this.firePropertyChange(DefaultController.BACKUP_DUMMY, i-1, i);
    }
}

在我看来,我有这个:

@Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        // .......


        else if( evt.getPropertyName().equals( DefaultController.BACKUP_DUMMY ) ){
            System.out.println("WHAT?");
            this.dummy.setText(evt.getNewValue().toString());
        }

    }

您可以想象每次都会打印 What?,但是直到循环完成才更新GUI. 当您使用SWING及其EDT时,这是典型的问题,我已经在oracle网站上阅读了

As you can imagine the WHAT? is printed every time but the GUI is not updated until the loop has finished is thing. That's the classic problem when you're working with SWING and its EDT and I've read on the oracle site this article/tutorial but I don't think I need to use a SwingWorker. I just need to update a single component on the GUI.

推荐答案

请勿将事件分发线程用于长时间运行的操作.您应该启动另一个线程以进行长时间运行的操作,例如文件复制.如果需要从辅助线程更新gui,则应使用SwingUtilities.invokeLater或SwingUtilities.invokeAndWait方法..

Do not use event dispatch thread for long running operation. You should start another thread for long running operation such as file copying. If you need to update your gui from the worker thread, you should use SwingUtilities.invokeLater or SwingUtilities.invokeAndWait methods..

作为示例;

final JLabel label = new JLabel();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
    public void actioPerformed(ActionEvent ev) {
         Thread workerThread = new Thread() {
               public void run() {
                     //do long running job then update ui
                   SwingUtilities.invokeLater(new Runnable() {
                           public void run(){
                               label.setText("Operation has finished");
                           }
                    });

               }
         }.start();    
    }
});

这篇关于当GUI不更新信息时,通过SWING和多线程处理GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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