1

//I am trying to set a timer for my minesweeper code using java, and below is my code for timer setting. It is supposed to be a 1000sec countdown, but somehow, the program will sometimes refresh and start over from 1050sec itself, which is very confusing. Can anyone help me to resolve the issue?

   public Board(JLabel timeBar, JLabel statusBar) {
    ...
    startTime = LocalDateTime.now().getSecond();
    // set timer
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (!gameOver) {
                int endTime = LocalDateTime.now().getSecond();
                int delta = endTime - startTime;
                if (delta >= 1000) {
                    gameOver = true;
                } else {
                    timeBar.setText(String.format("Time Remaining: %d", 1000 - delta));
                }
            }
        }
        
    }, 1000, 1000);
}
Mary Nie
  • 11
  • 1
  • Don't use a TimerTask. Updates to Swing components should be done on the Event Dispatch Thread (EDT). Instead you should be using a Swing Timer. – camickr May 10 '21 at 02:40

0 Answers0