I want to update my GUI each time I go trough a for loop, I can update my GUI when I manually update it, but in a loop it shows only the last update. I've heard and read abouth SwingWorker, but honestly I don't understand much of it, and the examples are different from what I need to do.
This is my loop :
for(int i = 0; i < 3; i++){
actionRoll();
}
and this is the method for updating my GUI:
public static void actionRoll() {
String uitkomst, dice1, dice2;
int isHonderd, isMexico;
// making instance of generator
Generator generator = new Generator();
//get info from generator
uitkomst = generator.getResults();
isHonderd = generator.getIfHunderd();
isMexico = generator.getIfMexico();
//split the result
String[] parts = uitkomst.split("-");
dice1 = parts[0];
dice2 = parts[1];
//setLeft Dice
ImageIcon image = new ImageIcon("img/diceSurface/diceSurface0"+dice1+".png");
((IconPanel) pnDiceLeft).setImage(image);
//setRightDice
ImageIcon image1 = new ImageIcon("img/diceSurface/diceSurface0"+dice2+".png");
((IconPanel) pnDiceRight).setImage(image1);
pnMainPanel.updateUI();
}
Now it only shows the third and thus last time of the loop, how to solve this? I tought about an thread.sleep() but it won't work..
Thanks in advance!
A assume you're executing the loop in some listener/action handler and thus in the event dispatch thread, which updates the ui. That would cause ui updates to be halted until the loop is executed and hence you only see the last iteration.
As you correctly said, using a SwingWorker should help, because the loop would then be executed by a different thread.
Example:
class ActionRollWorker extends SwingWorker<Void, String> {
public StringdoInBackground() {
for(int i = 0; i < 3; i++){
// making instance of generator
Generator generator = new Generator();
//get info from generator
String uitkomst = generator.getResults();
int isHonderd = generator.getIfHunderd();
int isMexico = generator.getIfMexico();
publish(uitkomst);
}
return null;
}
protected void process( List<String> chunks )
{
for( String uitkomst : chunks )
{
String[] parts = uitkomst.split("-");
String dice1 = parts[0];
String dice2 = parts[1];
//setLeft Dice
ImageIcon image = new ImageIcon("img/diceSurface/diceSurface0"+dice1+".png");
((IconPanel) pnDiceLeft).setImage(image);
//setRightDice
ImageIcon image1 = new ImageIcon("img/diceSurface/diceSurface0"+dice2+".png");
((IconPanel) pnDiceRight).setImage(image1);
}
}
protected void done() {
//nothing
}
}
Call it like:
new ActionRollWorker().execute();
Note that pnDiceLeft
etc. might either have to be passed to the worker or the worker needs to be an inner or anonymous class to have access to those variables, depending on how and where they are defined.
Also note that this is untested code and some things might be missing but it should get you started.