2015-11-02 100 views
0

我想在這個模式在我的JPanel顯示與計時器一個JLabel,例如:如何使用JLabel創建計時器?

03:50 sec 
03:49 sec 
.... 
.... 
00:00 sec 

所以我建立這個代碼:

@SuppressWarnings("serial") 
class TimeRefreshRace extends JLabel implements Runnable { 

    private boolean isAlive = false; 

    public void start() { 
     Thread t = new Thread(this); 
     isAlive = true; 
     t.start(); 
    } 

    public void run() { 
     int timeInSecond = 185 
     int minutes = timeInSecond/60; 
     while (isAlive) { 
      try { 
       //TODO 
      } catch (InterruptedException e) { 
       log.logStackTrace(e); 
      } 
     } 
    } 

}//fine autoclass 

有了這個代碼,我可以啓動JLabel

TimeRefreshRace arLabel = new TimeRefreshRace(); 
arLabel.start(); 

所以我有secondo的時間例如180秒,我如何創建計時器?

+0

使用javax.swing.Timer併爲每個滴答提供遞減。 –

回答

1

這裏是一個例子,如何構建倒計時標籤。您可以使用此模式創建您的組件。

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.Timer; 
import javax.swing.WindowConstants; 

public class TimerTest { 

    public static void main(String[] args) { 
     final JFrame frm = new JFrame("Countdown"); 
     final JLabel countdownLabel = new JLabel("03:00"); 
     final Timer t = new Timer(1000, new ActionListener() { 
      int time = 180; 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       time--; 
       countdownLabel.setText(format(time/60) + ":" + format(time % 60)); 
       if (time == 0) { 
        final Timer timer = (Timer) e.getSource(); 
        timer.stop(); 
       } 
      } 
     }); 
     frm.add(countdownLabel); 
     t.start(); 
     frm.pack(); 
     frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     frm.setVisible(true); 
    } 

    private static String format(int i) { 
     String result = String.valueOf(i); 
     if (result.length() == 1) { 
      result = "0" + result; 
     } 
     return result; 
    } 
} 
1

你可以在你的try塊調用事件調度線程(EDT)中並更新UI:

 try { 
      SwingUtils.invokeLater(new Runnable() { 
       @Override 
       public void run() { 
        this.setText(minutes + " left"); 
       } 
      } 
      //You could optionally block your thread to update your label every second. 
     } 

或者,你可以使用一個Timer而不是實際線程的,所以你的TimerRefreshRace將有自己的定時器週期性地觸發一個事件。然後,您將使用try-catch區塊中的相同代碼更新UI。