Java Swing计时器和ActionEvents的故障
我试图让一个JLabel显示日期并每秒更新一次。为此,我使用Swing的Timer类并实现我自己的名为DateTimer的类。DateTimer也是一个ActionListener 这是DateTimer:Java Swing计时器和ActionEvents的故障,java,swing,user-interface,date,timer,Java,Swing,User Interface,Date,Timer,我试图让一个JLabel显示日期并每秒更新一次。为此,我使用Swing的Timer类并实现我自己的名为DateTimer的类。DateTimer也是一个ActionListener 这是DateTimer: public class DateTimer implements ActionListener { private int delay; private JLabel label; private Calendar cal; public DateTime
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,他可能会想执行以下
Calendar.getInstance().getTime().toString()
Yep就是这样做的。谢谢你们两位。我正在使用Calendar.getInstance().getTime().toString()