How to slow down a for-loop? [duplicate]

余生长醉 提交于 2021-02-11 12:17:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!