Reputation: 1709
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'.
}
});
}
}
Upvotes: 1
Views: 449
Reputation: 328598
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).
Upvotes: 1