如何将计时器的秒数转换为hh:mm:ss格式?

4

如果我重复提问同一个问题被视为垃圾邮件,那么我真的很抱歉,因为我一个小时前已经问过了倒计时器的问题。

但现在遇到了新问题,尽管我无法再引起任何人对那个问题的关注。感谢你们,我已经成功编写了计时器,但是我尝试将秒转换为hh:mm:ss格式,但它没有起作用。它没有像预期的那样连续不断地倒计时至00: 00: 00,而只显示了我编写的时间。

这是我的代码。

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

3
这是通过众包进行编程吗? - Mitch Wheat
int seconds = 5; int hr = (int)(seconds/3600); 你期望小时数是多少?首先尝试在此网站上搜索答案:如何将毫秒转换为hhmmss格式 - Sage
不,我正在创建一个完整的软件,计时器只是其中的一部分,而且由于我是Java语言的初学者,我不太理解它。 - Hashan Wijetunga
如何使lab.setText(hrStr+ " : "+mnStr+ " : "+secStr+""); 也更新循环? - Hashan Wijetunga
显示剩余2条评论
2个回答

17

转移你的计算

  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; 

进入run方法。


1
两个'int'转换是冗余的,可以移除。 - ottel142

1
public String getCountDownStringInMinutes(int timeInSeconds)
{
    return getTwoDecimalsValue(timeInSeconds/3600) + ":" + getTwoDecimalsValue(timeInSeconds/60) + ":" +     getTwoDecimalsValue(timeInSeconds%60);
}


public static String getTwoDecimalsValue(int value)
{
    if(value>=0 && value<=9)
    {
        return "0"+value;           
    }
    else
    {
        return value+"";
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接