开发者

Handling GUI with SWING with multithreading when the GUI does not update informations

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(Integ开发者_如何学编程er 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);
    }
}

In my view I have this:

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


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

    }

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.


but the GUI is not updated until the loop has finished is thing.

This indicates that all your code is running on the EDT and therefore the GUI can't repaint itself until the entire loop finishes.

but I don't think I need to use a SwingWorker.

Why not, that is probably the easiest solution. You have your main loop run on a separate thread, and then you "publish" the results as each file is processed.

Or use the approach suggested by Gursel. The long running code is executing in a separate Thread and only the firing of the property change event is on the EDT, which means the GUI can repaint itself on the EDT.


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..

as an example ;

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();    
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜