Below is a SwingWorker instance that did not update the Java GUI as I had expected it to.
The SwingWorker is implemented inside an action listener for a button. The min
and max
which define the loop are both a "final int" which are local to the action listener.
The SwingWorker is supposed to on each iteration call the NQueens
object's go() method which recursively finds all the solutions for n-queens. Then the NQueens
object's toString()
is called after which the String is published so that the process() method will update the jProgressBar
and the jTextArea
. However nothing occurs when the button is pressed. Is this how I should be implementing an intensive process coupled with GUI component updates?
new SwingWorker <Void,String>()
{
private int totalPercent;
@Override
protected Void doInBackground()
{
int diff = max - min + 1;
int percent = 100;
if(diff != 0)
{
percent = 100/diff;
}
totalPercent = 0;
NQueens queens = new NQueens(min);
for(int j = min; j <= max; j++)
{
queens.go();
totalPercent += percent;
String newText = queens.toString();
publish(newText);
queens.nextSet();
}
isCalced = true;
return null;
}
protected void process(String results)
{
jTextArea2.append(results);
jProgressBar1.setValue(totalPercent);
jProgressBar1.repaint();
}
}.execute();