I am having trouble figuring out a way to call publish()
and/or setProgress()
when my time-consuming code is in a method that is not contained within the SwingWorker
.
To illustrate:
class Task extends SwingWorker<Void, Void> {
@Override
protected void process(List<Void> chunks) {
// Process
}
@Override
protected Void doInBackground() throws Exception {
getData(this);
return null;
}
@Override
protected void done() {
// Done.
}
}
public Object[][] getData(SwingWorker worker) {
worker.publish(); // <-- publish() is protected, unavailable from outside.
worker.setProgress(1); // <-- same with setProgress().
return new Object[0][0];
}
This code throws a compiler error because publish()
and setProgress()
are protected, and thus inaccessible even if you have the object.
Are there any workarounds to this? It would be unfortunate if everything needed to be contained inside the SwingWorker
to be published. My getData()
task is very time-consuming and I'd like to update the user on what's happening.
Hope this question makes sense.
You can always give your SwingWorker class public methods that other classes may call. These may be as simple as just a wrapper method for one of the protected methods:
public void mySetProgress(int progress) {
super.setProgress(progress);
}
A much better way:
Another way is to re-think your program structure -- have your object with the getData(...)
method return interim results that the SwingWorker can listen for via some sort of observing mechanism, and then have the worker call its publish method as needed.
Edit 2
You state in comment:
Both are solutions I thought about but they both seem to have unfortunate consequences. My getData() method has about 20 steps that I'd like to publish through. Making a program structure that returns interim results would require me to break it up into smaller methods and pass along the results to each method.. Just seems like too much work =/
No, no extra methods are needed. All your getData(...) method needs to do is to periodically update a class property and notify listeners. The listeners (here your SwingWorker) could then extract the class property and call publish with it.