带有Swing计时器和ActionEvent的问题

问题描述

| 我正在尝试让JLabel显示日期并每秒更新一次。为此,我使用了Swing \的Timer类,并实现了我自己的名为DateTimer的类。 DateTimer还是一个ActionListener。 这是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和处理操作的新手,请原谅我的无知。     

解决方法

        
java.util.Calendar.getInstance()
返回一个对象,该对象表示创建时的当前日期和时间。它不会像您假设的那样自动更新。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...