2016-03-25 28 views
0

我想創建一個可自定義選項的時鐘程序,但由於我是初學者,所以遇到了一些問題。我試過使用DigitalClock項目,但目前對我來說有太多的東西 我看着Timer和ScheduledExecuterService,但我不知道如何使用和放置它們。 我也試圖設置一個顏色的背景,但錯誤是,它可能是過度運行。 我怎樣才能以毫秒爲單位重複該過程,添加背景並使代碼更輕?如何重複該過程以顯示當前時間?

public Clock() { 
    initComponents(); 
    Calendar cal = new GregorianCalendar(); 
    int second = cal.get(Calendar.SECOND); 
    int minute = cal.get(Calendar.MINUTE); 
    int hour = cal.get(Calendar.HOUR_OF_DAY); 
    ///////////////////////////////////////////////////////////// 
    if (second < 10){ 
     time.setText(" "+hour+": "+minute+":0"+second+""); 
    } 
    else if (minute < 10){ 
     time.setText(" "+hour+":0"+minute+": "+second+""); 
    } 
    else if (hour < 10){ 
     time.setText("0"+hour+": "+minute+": "+second+""); 
    } 
    else if (hour < 10 & minute < 10){ 
     time.setText("0"+hour+":0 "+minute+": "+second+""); 
    } 
    else if (minute < 10 & second < 10){ 
     time.setText(" "+hour+":0"+minute+":0"+second+""); 
    } 
    else if (hour < 10 & minute < 10 & second < 10){ 
     time.setText("0"+hour+":0"+minute+":0"+second+""); 
    } 
    else { 
     time.setText(hour + " : " + minute + " : " + second+""); 
    } 
    //////////////////////////////////////////////////////////////// 

    } 
+1

您是否誤解'javascript'與'javascript'。他們都不同。 – Munawir

回答

0

如果你想讓它簡單,那麼你可以簡單做到以下幾點:

public static void main (String[] args) throws Exception 
{ 
    final SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss:SSS"); 
    while(true) { 
     System.out.println(sf.format(new Date())); 
     Thread.sleep(1); 
    } 
} 

但是,這可能會錯過在之間的毫秒項。例如,它可能會在308之後直接進入310,並在之間錯過309。但是因爲我們正在談論的是一秒鐘內的1/1000th,在現實生活中它是不太可能被注意到的。

您的代碼將減少類似如下:

public Clock() { 
    public static void main (String[] args) throws Exception { 
     initComponents(); 
     final SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss:SSS"); 
     while(true) { 
      time.setText = sf.format(new Date()); 
      Thread.sleep(1); 
     } 
    } 
} 
0
final SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss:SSS"); 
Timer timer = new Timer(); 
timer.schedule(new TimerTask() { 
     public void run() { 
      System.out.println(sf.format(new Date())); 
     } 
}, 0 , 1000000); 

將重複在1毫秒。

+0

這將在'1秒'而不是'1毫秒'中重複。 – user2004685