I use a class extending SwingWorker that looks as follows:
public class Analyzer extends SwingWorker<Integer, Object> {
String source;
public Analyzer(String simulation, DBConnector connection)
throws ClassNotFoundException, SQLException, IOException {
super();
source=simulation;
//creating several objects that get their data from a DB and will be "analyzed" in the background
}
@Override
protected Integer doInBackground() {
tripAnalyzer ta = new tripAnalyzer();
if (trips.getIterator().hasNext()) {
if (isCancelled()) {
trips.close();
ta.cancelFinish();
return FAILED;
}
ta.init(null, null, false);
while (trips.getIterator().hasNext()) {
setProgress(trips.getProgress());
ta.prepare(source, trips.getIterator().next());
}
//export the results to a text-file
return SUCCESS;
}
}
@Override
protected void done() {
setProgress(100);
trips.close();
super.done();
}
}
The simulation String value comes from a JTable. So far it all works fine for one "simulation key" but now I want to expand this to be able to do the Worker stuff for several "simulation keys". One approach I thought of could be to pass an array or list of Strings with simulation keys and change the constructor appropriately. But that would become utterly clumpy as I would have to create lots of objects during the execution of the constructor and there is A LOT of data to be processed. I could also create a separate constructor specifically for an array of Strings but that would be copy/paste of approx 60 lines of code and there would be the issue of clumpiness.
My idea was to reinstantiate the Analyzer class with a different simulation key when analysis on a previous simulation was done. (yes I know instantiating the same SwingWorker several times during EDT does not invoke the doInBackground method more than once. But once it's done and off the hook it should work... in my head at least :)). But right now I hit a wall and don't really know how to proceed.
The workflow should be like this:
1: I choose f.ex. 3 simulation keys from a JTable stored in an array or list [1,2,3]
2: then the Worker gets instantiated from my GUI-class and does his work on the first key i.e. '1'
3: after work on '1' is done the worker should be reinstantiated and start working on '2'
4: and so on until all simulation keys have been processed.
Maybe my thinking is too stiff and there are better ways to accomplish this therefore any help at all to point me in the right direction will be greatly appreciated! Thanks
EDIT
public Analyzer(String simulation, DBConnector connection){
this(new String[]{simulation}, connection);
source = simulation;
}
public Analyzer(String[] simulation, DBConnector connection){
super();
for( String s : simulation) this.simulations.add(s);
this.connection = connection;
}
As mentioned in the comments below the publish()
method wasn't needed as the statusbar updates correctly.
The list where I put all the keys is a LinkedList that gets stripped of a key during every loop cycle until it is empty.