2014-12-03 91 views
0

我有一个迷宫,机器人可以移动并探索。我试图使用计时器重新绘制,因为机器人移动但计时器由于某种原因不踢。这不是拖延程序,所以我不能看到重新绘制过程。这里是我的代码:使用计时器重新绘制

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

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

回答

-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

+0

你知道的方式,使用摆动计时器?我不想改变这个程序。这种方法适用于不同的程序。它一定是一个简单的修复。我只是不知道如何解决它... – JOH 2014-12-03 17:22:02

0

尝试使用不** updateDrawing(迷宫)**但是这种方法:

无效updateMaze(){

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

谢谢,但是没有工作...计时器仍然没有踢... – JOH 2014-12-03 17:20:39