问题
If I had a method inside the doInBackground() that belongs to other class is it possible to set setProgess() based on changes that happen in that other method of an outside class?
回答1:
You state:
but when I put setProgess() inside the method of another class it tells me that I need to make that method.
This has nothing to do with SwingWorker and all to do with basic Java. No class can call another classes instance (non-static) methods without doing so on a valid instance of the class. For your code to work, the "other" method must call setProgress(...)
on an instance of the SwingWorker, and so you must pass a reference of the SwingWorker to that other class. So pass the SwingWorker (this
inside of the SwingWorker) into the other class, and then you can happily call its methods. Again, this has nothing to do with threading, Swing, or SwingWorkers, but rather is basic bread and butter Java.
Edit: since setProgress is protected and final, your SwingWorker will have to have a public method that the other class can call, and in this method the SwingWorker will need to call its own setProgress(...)
method.
e.g.,
MyWorker class
public class MyWorker extends SwingWorker<Integer, Integer> {
private OtherClass otherClass;
public MyWorker() {
otherClass = new OtherClass(this);
}
@Override
protected Integer doInBackground() throws Exception {
otherClass.otherMethod();
return null;
}
// public method that exposes setProgress
public void publicSetProgress(int prog) {
setProgress(prog);
}
}
OtherClass:
class OtherClass {
MyWorker myWorker;
public OtherClass(MyWorker myWorker) {
this.myWorker = myWorker;
}
public void otherMethod() {
for (int i = 0; i < 100; i++) {
myWorker.publicSetProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
}
}
回答2:
As long you are concerned that you have to update the bar, you can achieve it anywhere where you have access to the instance, by calling the appropriate methods. It is not dependent to a method or class. (this is true for every object, in Java).
Per your comment, you should pass a reference to the bar, as a parameter in that method. Otherwise, you won't have access to it.
来源:https://stackoverflow.com/questions/13717826/java-progress-bar-is-it-possible-to-use-setprogess-of-progress-bar-outside