New to SwingWorker how to use process?
I'm new to multi-threads and am encountering an issue I can't figure out. I have built a simple class extending SwingWorker and all I want it to do is have it run a long running task in the doInBackground method. I also want to test the publish/process function so I attempted to have the process increment an int counter and display it on my GUI. Here is code:
Code Java:
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;
public class CounterWorker extends SwingWorker<Integer, Integer> {
private MainGUI gui;
private int counter;
public CounterWorker(MainGUI gui) {
this.gui = gui;
this.counter = 0;
}
@Override
protected Integer doInBackground() throws Exception {
for (int i = 0; i < 100; i++) {
counter++;
publish(counter);
Thread.sleep(10);
}
return 10;
}
protected void process(Integer count) {
int c = count;
gui.setCounterLabel(Integer.toString(c));
}
@Override
protected void done() {
gui.setStatusLabel("Finished");
try {
gui.setMainLabel(get().toString());
} catch (InterruptedException ex) {
Logger.getLogger(CounterWorker.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(CounterWorker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The doInBackground eventually is finished and done runs, but process never does anything (I don't see the counter). Is this even do-able? I appreciate the help.
Re: New to SwingWorker how to use process?
If you put an @Override annotation above your process method, your code won't compile, and that's because its method signature is wrong and doesn't override a parent method. The method should accept a List<Integer> parameter, not an Integer parameter. You should then iterate through the List<Integer> setting your counter label with it:
Code :
@Override // don't forget this
protected void process(List<Integer> chunks) {
for (Integer chunk : chunks) {
// no need for the c variable
gui.setCounterLabel(chunk.toString());
}
}
Re: New to SwingWorker how to use process?
Everything makes sense now, thank you so much.
Re: New to SwingWorker how to use process?