我正在开发一个程序,它会计算点击按钮之前的时间 我在使用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();
答案 0 :(得分:2)
您已在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();
这使得管理单个值然后决定如何最好地格式化它,而不是管理三个状态这一事实变得更加简单......恕我直言
答案 1 :(得分:1)
如果我了解你,你应该先存储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);