问题
I am creating an app that finds the shortest path in a maze, using JavaSwing. I have a two-dimensional matrix, both logical and graphical, made up of JLabel's, which I can use to paint paths and walls.
So far I have this:
As you can see, the start node moved from a position to another position, and draws a path of the route that he made.
To verify that the path is free and does not collide with a wall (red JLabels) I have a for-loop that is responsible for checking if the path is clear.
if(posCol < 25 && posRow <25){
labels2D[posRow][posCol].runner = false;
int posRowf = posRow; // Final y position
int posColf = posCol; // Final x position
// Implementing the "move right" algorithm (for now)
fr : for(int col = posCol; col<25; col++){
// Verify is the cell is not a wall
if(labels2D[posRow][col].block == false){
// If it's not a wall then draw a road
// Assign these as the final possible positions
labels2D[posRow][col].changeColor(Color.GRAY);
labels2D[posRow][col].setText("-");
posRowf = posRow;
posColf = col;
}else{
break fr;
}
}
labels2D[posRowf][posColf].runner = true;
labels2D[posRowf][posColf].changeColor(Color.GREEN);
labels2D[posRowf][posColf].setText("");
}
MY PROBLEM:
I need each iteration of the for to make a kind of "pause" to paint the components to visualize an "animation".
I already tried using:
private void delay(long ms){
try {
Thread.sleep(ms);
} catch (Exception ex) {
}
}
I call the delay()
method inside the for, and I notice that it does make the pauses in each iteration, but for some reason it does not paint the JLabels one by one. Only when the foor loop is done is that it suddenly paints all the components.
Any help would be appreciated. Thanks in advance :)
来源:https://stackoverflow.com/questions/64164347/how-to-slow-down-a-for-loop