开发者

Troubles with Swing Timer and ActionEvents

开发者 https://www.devze.com 2023-03-13 03:36 出处:网络
I\'m trying to get a JLabel to display the dat开发者_StackOverflow中文版e and update every second. To do this I\'m using Swing\'s Timer class and implementing my own class called DateTimer. DateTimer

I'm trying to get a JLabel to display the dat开发者_StackOverflow中文版e and update every second. To do this I'm using Swing's Timer class and implementing my own class called DateTimer. DateTimer is also an ActionListener.

This is 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());
    }

}

I call this from somewhere else in my code like this:

new DateTimer(1000, this.label);

I get the date to display once, then it doesn't ever update.

I'm new to Java GUIs and handling actions so please excuse my ignorance.


java.util.Calendar.getInstance() returns an object representing the current date and time at the time it is created. It doesn't update automatically as you are assuming.

0

精彩评论

暂无评论...
验证码 换一张
取 消