Dynamic Clock in java

后端 未结 7 1054
我在风中等你
我在风中等你 2020-12-16 02:22

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

7条回答
  •  温柔的废话
    2020-12-16 03:12

    This sounds like you might have a conceptual problem. When you create a new java.util.Date object, it will be initialised to the current time. If you want to implement a clock, you could create a GUI component which constantly creates a new Date object and updates the display with the latest value.

    One question you might have is how to repeatedly do something on a schedule? You could have an infinite loop that creates a new Date object then calls Thread.sleep(1000) so that it gets the latest time every second. A more elegant way to do this is to use a TimerTask. Typically, you do something like:

    private class MyTimedTask extends TimerTask {
    
       @Override
       public void run() {
          Date currentDate = new Date();
          // Do something with currentDate such as write to a label
       }
    }
    

    Then, to invoke it, you would do something like:

    Timer myTimer = new Timer();
    myTimer.schedule(new MyTimedTask (), 0, 1000);  // Start immediately, repeat every 1000ms
    

提交回复
热议问题