[英]How to update time elapsed
我正在開發一個程序,該程序將計算單擊按鈕之前的時間,但我無法使用Timer。 我想要像00:00:00-> 00:00:01-> 00:00:02 ...
它卡在00:00:01
這是我的代碼
Timer timer=new Timer(1000,null);
JLabel time=new JLabel("00:00:00");
timer.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
DecimalFormat df=new DecimalFormat("00");
int h=0;
int m=0;
int s=0;
s++;
if(s==60)
{
m++;
if(m==60)
{
h++;
}
}
time.setText(df.format(h)+":"+df.format(m)+":"+df.format(s));
revalidate();
repaint();
}
});
timer.start();
您已經在ActionListener
的上下文中將變量聲明為局部變量。
@Override
public void actionPerformed(ActionEvent e)
{
DecimalFormat df=new DecimalFormat("00");
int h=0;
int m=0;
int s=0;
這意味着每次將actionPerformed
變量重置為0
...
嘗試使它們成為實例變量...
例如,當變量超過限制時,您也不會重置它們。
s++;
if (s >= 60) {
s = 0;
m++;
if (m >= 60) {
h++;
m = 0;
}
}
或者,您可以維護一個計數器,該計數器用作已過去的秒數,並使用一些模塊數學來計算時間部分
private int count = 0;
//...
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count++;
int hours = count / (60 * 60);
float remainder = count % (60 * 60);
float mins = remainder / (60);
remainder = remainder % (60);
float seconds = remainder;
DecimalFormat df=new DecimalFormat("00");
time.setText(df.format(hours) + ":" + df.format(mins) + ":" + df.format(seconds));
}
});
timer.start();
這使得您管理單個值,然后決定如何最好地設置其格式,而不是管理三個狀態,這一點使事情變得更加簡單。
如果我了解您,則應首先存儲startTime-
final long startTime = System.currentTimeMillis();
然后使用它來計算actionPerformed()
時間字段,
DecimalFormat df = new DecimalFormat("00");
long endTime = System.currentTimeMillis();
long diff = endTime - startTime;
int h = (int) (diff) / (60*60*1000);
diff -= h * (60*60*1000);
int m = (int) (endTime-startTime) / (60*1000);
diff -= m * (60 * 1000);
int s = (int) (diff / 1000);
time.setText(df.format(h) + ":" + df.format(m)
+ ":" + df.format(s));
revalidate();
repaint();
編輯
根據您的新要求,
更換
final long startTime = System.currentTimeMillis();
同
final Calendar startTime = Calendar.getInstance();
接着
DecimalFormat df = new DecimalFormat("00");
long endTime = System.currentTimeMillis();
long diff = endTime - startTime.getTimeInMillis();
int h = (int) (diff) / (60 * 60 * 1000);
diff -= h * (60 * 60 * 1000);
int m = (int) (endTime - startTime.getTimeInMillis()) / (60 * 1000);
diff -= m * (60 * 1000);
int s = (int) (diff / 1000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.