2016-12-30 89 views
-1

我正在編寫我的第一個Java遊戲的代碼,到目前爲止我已經構建了GUI並且我想添加一些邏輯。在我的遊戲中,用戶應該看到他的移動時間(從10秒開始),例如10,9,8,7,6,5,4,3,2,1,0。我創建了JLabel並希望顯示流逝它的時間。我的程序有三個難度等級,首先用戶通過點擊適當的JButton選擇一個,然後用戶應該看到定時器和一些選項來選擇和播放。我該如何處理這個問題?我讀了Java中的Timer類,但仍不知道如何在JLabel上顯示倒計時。也許我應該實現一個遊戲循環,但說實話,我不知道如何做到這一點。Java - 如何使一個計時器在JLabel中顯示流逝的時間

+0

試過什麼了嗎? – GurV

+0

我正在尋找解決方案,現在我想了解一個遊戲循環,以及如何使用計時器連接它也許 – JeffTheKiller

+0

這個http://compsci.ca/v3/viewtopic.php?t=25991可以讓你開始。但是,g.drawImage調用不是在Swing的事件調度線程上完成的,需要修復(SwingUtilities?) –

回答

0

您可以簡單地使用倒數計時器方法,並將您的JLabel以及遞減計數的秒數和可選的「結束時間」消息傳遞給它。

有很多這種在互聯網上的東西的例子,但這裏是我的一個快速再現:

public static Timer CountdownTimer(JLabel comp, int secondsDuration, String... endOfTimeMessage) {           
    if (secondsDuration == 0) { return null; } 
    String endMsg = "~nothing~"; 
    if (endOfTimeMessage.length>0) { endMsg = endOfTimeMessage[0]; } 
    final String eMsg = endMsg; 
    int seconds = secondsDuration; 
    final long duration = seconds * 1000; 
    JLabel label = (JLabel)comp; 
    final Timer timer = new Timer(10, new ActionListener() { 
     long startTime = -1; 
     @Override 
     public void actionPerformed(ActionEvent event) { 
      if (startTime < 0) { 
       startTime = System.currentTimeMillis(); 
      } 
      long now = System.currentTimeMillis(); 
      long clockTime = now - startTime; 
      if (clockTime >= duration) { 
       ((Timer)event.getSource()).stop(); 
       if (!eMsg.equals("~nothing~")) { label.setText(eMsg); } 
       return; 
      } 
      SimpleDateFormat df = new SimpleDateFormat("mm:ss:SSS"); 
      label.setText(df.format(duration - clockTime)); 
     } 
    }); 
    timer.start(); 
    return timer; 
} 

如果你想改變計數減少被選擇JLabel中顯示,然後一路您可以更改SimpleDateFormat字符串。這個方法返回Timer對象,所以......你想知道如何隨時停止它(在持續時間到期之前)。