簡體   English   中英

Swing 定時器和 ActionEvents 的問題

[英]Troubles with Swing Timer and ActionEvents

我正在嘗試讓 JLabel 顯示日期並每秒更新一次。 為此,我使用 Swing 的計時器 class 並實現我自己的 class,稱為 DateTimer。 DateTimer 也是一個 ActionListener。

這是日期定時器:

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 和處理操作的新手,所以請原諒我的無知。

java.util.Calendar.getInstance()返回一個 object 代表創建時的當前日期和時間。 它不會像您假設的那樣自動更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM