2011-06-13 51 views
2

我試圖讓JLabel顯示日期和每秒更新一次。爲此,我使用了Swing的Timer類,並實現了我自己的類DateTimer。 DateTimer也是一個ActionListener。擺動計時器和ActionEvents的問題

這是DateTimer:

public class DateTimer implements ActionListener { 
    private int delay; 
    private JLabel label; 
    private Calendar cal; 

    public DateTimer(int delay, JLabel label) { 
     this.delay = delay; 
     this.label = label; 

     cal = Calendar.getInstance(); 
     new Timer(this.delay, this).start(); 
    } 

    public void actionPerformed(ActionEvent e) { 
     this.label.setText(this.cal.getTime().toString()); 
    } 

} 

我在代碼中調用這個從別的地方是這樣的:

new DateTimer(1000, this.label); 

我得到的日期顯示一次,那麼它不會永遠更新。

我是新來的Java GUI和處理操作,所以請原諒我的無知。

回答

7

java.util.Calendar.getInstance()返回表示當前日期和時間在創建時的對象。它不會像您所假設的那樣自動更新。

+0

+1,而是他可能會想要做以下'Calendar.getInstance()。getTime()。toString()' – mre 2011-06-13 16:09:10

+0

是的,它做到了。感謝你們倆。我使用Calendar.getInstance()。getTime()。toString() – n0pe 2011-06-13 16:11:19