簡體   English   中英

使用計時器重畫

[英]Using timer to repaint

我有一個迷宮,機器人可以四處走動和探索。 我正在嘗試使用計時器在機器人移動時進行重新繪制,但是由於某些原因計時器沒有啟動。 它沒有延遲程序,所以我看不到重新繪制過程。 這是我的代碼:

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;
        }
    }
}

誰能告訴我為什么? 謝謝!

嘗試不使用** updateDrawing(maze)**,而是使用以下方法:

void updateMaze(){

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

這是制作基本計時器的方法。

計算顯示時間所需要做的就是記錄計時器啟動的時間:

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 ==您想要的任何值。

Java中的簡單計時器開始

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM