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?
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) {}
}
}
}