使用计时器重绘

时间:2014-12-03 16:41:25

标签: java timer repaint maze

我有一个迷宫,机器人可以四处走动探索。我尝试使用计时器重新绘制,因为机器人移动但计时器由于某种原因没有踢。它没有延迟程序,所以我看不到重画过程。这是我的代码:

public void updateDrawing(Maze maze) {  
    // 1000 millisecond delay
    Timer t = new Timer(1000, new TimerListener(maze));
    t.start();
}

private class TimerListener implements ActionListener {
    private Maze maze;

    public TimerListener(Maze maze) {
        super();
        this.maze = maze;
    }

    public void actionPerformed(ActionEvent e) {
        maze.repaint();
    }
}

public void explore (int id, Maze maze) {
    visited.add(maze.getCell(row, col));
    //Loop until we find the cavern 
    outerloop: //Label the outerloop for breaking purposes
    while(!foundCavern){
        //Move to a Cell
        Cell validCell = chooseValidCell(maze);
        //If validCell is null then we have to backtrack till it's not
        if(validCell == null){
            while(chooseValidCell(maze) == null){
                //Go back in route till we find a valid cell
                Cell lastCell = route.pollLast();
                if(lastCell == null){ //Implies we didn't find cavern, leave route empty
                    break outerloop;
                }
                this.row = lastCell.getRow();
                this.col = lastCell.getCol();
                updateDrawing(maze); // <- this calls repaint using timer
            }
            //Add back the current location to the route
            route.add(maze.getCell(row, col));
            validCell = chooseValidCell(maze);
        }
        this.row = validCell.getRow();
        this.col = validCell.getCol();
        updateDrawing(maze); // <- this calls repaint using timer
        //Add to the route 
        route.add(validCell);
        //Add to visited
        visited.add(validCell);
        //Check if we're at the cavern
        if(row == targetCavern.getRow() && col == targetCavern.getCol()){
            foundCavern = true;
        }
    }
}

谁能告诉我为什么?谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用不是** updateDrawing(maze)**但是这个方法:

void updateMaze(){

    EventQueue.invokeLater(()->updateDrawing(maze));
}

答案 1 :(得分:-1)

以下是制作基本计时器的方法。

计算显示时间所需要做的就是记录计时器开始的时间:

long startTime = System.currentTimeMillis();

稍后,当您想要显示时间量时,只需从当前时间中减去它。

long elapsedTime = System.currentTimeMillis() - startTime;
long elapsedSeconds = elapsedTime / 1000;
long secondsDisplay = elapsedSeconds % 60;
long elapsedMinutes = elapsedSeconds / 60;
//put here code to format and display the values

你可以让程序等到elapsedSeconds ==你想要的任何值。

来自Make a simple timer in Java