I have a maze where robots can move around and explore. I'm trying to use the timer to repaint as the robot move but timer's not kicking in for some reason. It's not delaying the program so I can't see the repainting process. Here's my code:
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;
}
}
}
Can anyone tell me why? Thank you!
try use not ** updateDrawing(maze)** but this method:
void updateMaze() {
EventQueue.invokeLater(()->updateDrawing(maze));
}
Here's how to make a basic timer.
All you need to do to calculate the time to display, is to record the time that the timer started:
long startTime = System.currentTimeMillis();
Later, when you want to display the amount of time, you just subtract this from the current time.
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
You can make your program wait until elapsedSeconds == whatever value you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.