2011-05-29 54 views
3

我創建了一個遊戲,並在我的swing界面中添加了一個計時器。我現在這樣做的方式是有一個當前時間的場,用System.currentTimeMillis()得到它,當遊戲開始時,它獲得它的價值。在我的遊戲方法中,我把System.currentTimeMillis() - 場;它會告訴你遊戲開始後的當前時間。如何在JLabel上更新自己的計時器

不過,如何讓它每秒更新一次呢,所以JLabel會有:timePassed:0s,timePassed:1s等等。請記住,我不會在任何時候在我的遊戲中使用線程。

編輯:謝謝大家的親切建議。我用了你的答案的組合,請給我一些反饋。

我把jlabel作爲一個叫做time的字段。 (否則我不能處理它)。

time = new JLabel("Time Passed: " + timePassed() + " sec"); 
    panel_4.add(time); 

    ActionListener actionListener = new ActionListener() { 
     public void actionPerformed(ActionEvent actionEvent) { 
      time.setText("Time Passed: " + timePassed() + " sec"); 
     } 
    }; 
    Timer timer = new Timer(1000, actionListener); 
    timer.start(); 
+2

答案在問題中。如果您使用Swing,請查看http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html – 2011-05-29 15:16:40

+1

,然後確實使用線程。你不可能在美國東部時間做任何事情! – jfpoilpret 2011-05-29 15:39:00

+0

錯誤。是的,我可以:P我的GUI是用於從一個顯示導航到另一個,即主菜單到播放屏幕到選項屏幕等。雖然2或3窗口可以保持打開在任何給定的時間,我永遠不會有一個用於窗口重複。那麼問題是什麼? – Martinos 2011-05-29 18:15:48

回答

3
new Thread(new Runnable 
{ 
    public void run() 
    { 
     long start = System.currentTimeMillis(); 
     while (true) 
     { 
      long time = System.currentTimeMillis() - start; 
      int seconds = time/1000; 
      SwingUtilities.invokeLater(new Runnable() { 
       public void run() 
       { 
         label.setText("Time Passed: " + seconds); 
       } 
      }); 
      try { Thread.sleep(100); } catch(Exception e) {} 
     } 
    } 
}).start(); 
+0

絕對不要在EDT之外訪問Swing組件('label.setText(...)')! – jfpoilpret 2011-05-29 15:37:19

+0

@jfpoilpret:什麼是替代方案?如何在不使用標籤更新器循環鎖定EDT的情況下使其工作。 – 2011-05-29 15:41:47

+0

@Martinos:與霍華德的Swing計時器推薦一起使用。雖然Marijn表示不錯,但他的回答不被推薦。 – 2011-05-29 15:42:26

0

wirite這在構造

的ActionListener taskPerformer =新的ActionListener(){

   @Override 

      public void actionPerformed(ActionEvent evt) { 
       jMenu11.setText(CurrentTime()); 
      } 
     }; 

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

這寫出構造

公共字符串CURRENTTIME(){

 Calendar cal = new GregorianCalendar(); 
     int second = cal.get(Calendar.SECOND); 
     int min = cal.get(Calendar.MINUTE); 
     int hour = cal.get(Calendar.HOUR); 
     String s=(checkTime(hour)+":"+checkTime(min)+":"+checkTime(second)); 
     jMenu11.setText(s); 
     return s; 

    } 

    public String checkTime(int t){ 
String time1; 
if (t < 10){ 
    time1 = ("0"+t); 
    } 
else{ 
    time1 = (""+t); 
    } 
return time1; 

}

6

這是我將如何設置我的JLabel更新與時間&日期。

Timer SimpleTimer = new Timer(1000, new ActionListener(){ 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     jLabel1.setText(SimpleDay.format(new Date())); 
     jLabel2.setText(SimpleDate.format(new Date())); 
     jLabel3.setText(SimpleTime.format(new Date())); 
    } 
}); 
SimpleTimer.start(); 

這,然後添加到您的主類和J​​Label1所做/ 2/3獲得與計時器更新。

+0

謝謝,太有幫助了 – EvilThinker 2015-02-06 17:42:17