2017-10-07 55 views
-2

我已經在GUI上設置並顯示了一個計時器。如何將整數分割爲字符串並自動以秒/分/小時爲單位進行轉換

我希望程序節省時間並加載它。我成功地做到了,但是, 我希望在程序啓動時加載previou時間。

ms是毫秒,所以如果它通過1000,它將它轉換爲1秒,並再次得到0的值。我創建了第二個(毫秒定時器)作爲(分數)來顯示,而不是將其更改爲0.在計時器停止之前,分數不會自行重置。

我想抓住得分和與訂單獲取的值提取:

分鐘//毫秒

我試圖提取它或不同數量的劃分,但它太困難對我說:/

簡單地說,我想自動檢測分的長度,並獲得一個會議紀要,秒和毫秒字符串並在JLabel後顯示。

我可以創建其他整數爲milliBackup,secondsBackup,minuteBackup。 並分別將它們傳遞給毫秒/秒/分鐘。但是,如果可以的話,我想這樣做。

public void beginTimer() { 

      score++; 
      ms++; 

      if(ms==1000) { 

       ms = 0; 
       s++; 

       if(s>59) { 

        s = 0; 
        m++; 

        if(m>59) { 

         timer.cancel(); 

        } 
       } 

      } 

      lblTimer.setText(displayTimer()); 

     } 

和DisplayTimer有:

public String displayTimer() { 
      return String.format("%02d:%02d:%03d", m, s, ms); 
     } 
+0

這是更好地使用Java'日期時間API'。看看http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html – Nolequen

回答

0

如何從score計算分(m),秒(s)和毫秒(ms):

ms = score; 
s = ms/1000; // integer div 
ms = ms % 1000; // remainder 
m = s/60; // integer div 
s = s % 60; // remainder 
1

你不說你是如何更新的方法。如果您打電話給Thread.sleep,應該格外小心。有更好的方法。但是,使用您的代碼:

// bad use of static but once you'll get it working, change it 
static long s = 1; 
static long m = 1; 
static long ms = 1; 

// the method is not beginTimer but updateTimer and goes inside a 
// loop or something which calls it agan and again 
public void updateTimer() { 

     if(ms==1000L) {     
      ms = 0; 
      s++; 

      if(s==60L) {      
       s = 0; 
       m++; 

       if(m==60L) {       
        timer.cancel();       
       } 
      }     
     }    
     lblTimer.setText(displayTimer());    
    } 
+0

我從util包使用定時器。這裏是cod:timer = new Timer(); \t \t \t \t \t \t \t \t \t \t的TimerTask的TimerTask =新的TimerTask(){ \t \t \t \t \t \t @Override \t \t \t \t \t \t公共無效的run(){ \t \t \t \t \t \t \t \t \t \t \t \t \t \t beginTimer(); \t \t \t \t \t \t \t \t \t \t \t \t \t} \t \t \t \t \t \t \t \t \t \t \t}; \t \t \t \t \t \t \t \t \t \t timer.scheduleAtFixedRate(TimerTask的,1,1); – Erick

+0

不錯。請記住,'TimerTask'不保證實時執行。例如。不能確保它在確切的毫秒內更新計數器。但從長遠來看,肯定會更新正確的**次數**。 –

+0

嗯..運行最精確的計時器的最佳方式是什麼? – Erick

相關問題