简体   繁体   中英

How do I call the invokeLater method from a thread in Java?

Ok, this is my problem:

I am trying to build a custom download helper for one of my projects. I wanted my implementation to allow multiple downloads (running simultaneously) so I figured that I should start a thread for every download.

However, the problem is that I also want to update the GUI of my program. To do that, I wanted to use the invokeLater() method since Swing is not thread-safe.

Now: If I use the invokeLater() method inside each thread to update a progressbar, how would a thread know about my GUI? Please let my know what you think about this approach and how you would solve this problem.

Please consider this aswell:

public class frame extends JFrame {
    public frame() {
        //the constructor sets up the JProgressBar and creates a thread object
    }

    public void getFiles() {
        // Here I would start the thread.
        thread.start();
    }
}

And here is another class that sets up the thread:

public class theThread extends Thread {
    // Here I would create the thread with its constructor 

    public void run() {
        // Here comes some code for the file download process
        //
        // While the thread is running the method below gets called.
        updateGUI();
    }

    public void updateGUI() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Here I need to place the code to update the GUI
                // However, this method has no idea of what the GUI looks like
                // since the GUI was setup in the class 'frame'.
            }
        });
    } 
}    

You could have a constructor that takes the frame as a parameter:

public class TheThread extends Thread {
    private final JFrame frame;

    public TheThread(Runnable r, JFrame frame) {
        super(r);
        this.frame = frame;
    }
}

Now you can call frame.doSomething(); from your updateGUI method.

Note that it is generally better practice to implement Runnable than to extend Thread .

Alternatively, you could use SwingWorkers which have been designed to handle situations like what you describe (background thread that updates the UI).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM