Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert seconds of Timer to hh:mm:ss?

Tags:

java

timer

I am truely sorry if asking the same question twice is considered spamming as I already asked about backward timer a hour ago.

But now new problem with it is though I couldn't get anyone's attention to that question again. I have successfully coded the timer thanks to you guys but then I tried to convert seconds tot he hh:mm:ss format but it didn't work. Instead of continuosely going till it is 00:00:00. It just shows the time that I coded it and that's it.

Here's my code.

import java.util.Timer;
import java.util.TimerTask;
public class countdown extends javax.swing.JFrame {


public countdown() {
    initComponents();
    Timer timer;

    timer = new Timer();
    timer.schedule(new DisplayCountdown(), 0, 1000);
}

class DisplayCountdown extends TimerTask {

      int seconds = 5;
      int hr = (int)(seconds/3600);
      int rem = (int)(seconds%3600);
      int mn = rem/60;
      int sec = rem%60;
      String hrStr = (hr<10 ? "0" : "")+hr;
      String mnStr = (mn<10 ? "0" : "")+mn;
      String secStr = (sec<10 ? "0" : "")+sec; 

      public void run() {
           if (seconds > 0) {
              lab.setText(hrStr+ " : "+mnStr+ " : "+secStr+"");
              seconds--;
           } else {

              lab.setText("Countdown finished");
              System.exit(0);
          }    
    }
}     
public static void main(String args[]) {
    new countdown().setVisible(true);
}  
like image 909
Hashan Wijetunga Avatar asked Dec 02 '22 18:12

Hashan Wijetunga


1 Answers

Move your calculations

  int hr = seconds/3600;
  int rem = seconds%3600;
  int mn = rem/60;
  int sec = rem%60;
  String hrStr = (hr<10 ? "0" : "")+hr;
  String mnStr = (mn<10 ? "0" : "")+mn;
  String secStr = (sec<10 ? "0" : "")+sec; 

into the run method.

like image 162
Origineil Avatar answered Dec 16 '22 23:12

Origineil