java中的动态时钟 [英] Dynamic Clock in java

查看:269
本文介绍了java中的动态时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的程序中实现一个时钟,以便在程序运行时显示日期和时间。我查看了 getCurrentTime()方法和计时器,但它们似乎都没有按照我的意愿行事。



问题是我可以在程序加载时得到当前时间,但它永远不会更新。任何有待观察的建议都将不胜感激!

解决方案

你需要做的是使用Swing的 计时器 只需让它每秒运行一次并用当前时间更新时钟。

 计时器t =新计时器(1000,updateClockAction); 
t.start();

这将导致 updateClockAction 触发一次一秒。它将在EDT上运行。



您可以使 updateClockAction 类似于以下内容:

  ActionListener updateClockAction = new ActionListener(){
public void actionPerformed(ActionEvent e){
//假设时钟是自定义的component
yourClock.setTime(System.currentTimeMillis());
// OR
//假设时钟是JLabel
yourClock.setText(new Date()。toString());
}
}

因为这会每秒更新时钟,所以时钟将会在更糟糕的情况下,将关闭999毫秒。要将此值增加到更差的99ms的错误边际,您可以增加更新频率:

 计时器t =新计时器(100 ,updateClockAction); 


I want to implement a clock within my program to diusplay the date and time while the program is running. I have looked into the getCurrentTime() method and Timers but none of them seem to do what I would like.

The problem is I can get the current time when the program loads but it never updates. Any suggestions on something to look into would be greatly appreciated!

解决方案

What you need to do is use Swing's Timer class.

Just have it run every second and update the clock with the current time.

Timer t = new Timer(1000, updateClockAction);
t.start();

This will cause the updateClockAction to fire once a second. It will run on the EDT.

You can make the updateClockAction similar to the following:

ActionListener updateClockAction = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
      // Assumes clock is a custom component
      yourClock.setTime(System.currentTimeMillis()); 
      // OR
      // Assumes clock is a JLabel
      yourClock.setText(new Date().toString()); 
    }
}

Because this updates the clock every second, the clock will be off by 999ms in a worse case scenario. To increase this to a worse case error margin of 99ms, you can increase the update frequency:

Timer t = new Timer(100, updateClockAction);

这篇关于java中的动态时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆