1

当您单击按钮时,我试图在文本字段上显示实际的系统时间显示。到目前为止,如果您每次单击按钮,它只会显示实时结果。我正在努力附加 ActionListener 以便时间可以不断更新。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date time = new Date();

    dateFormat.format(time);
    ActualTime.setText(dateFormat.format(time)); 

    Calendar cal = Calendar.getInstance();
    ActualTime.setText(dateFormat.format(cal.getTime()));
}                            
4

1 回答 1

3

感谢您编辑您的问题。

  • 要让时间不断自我更新,请使用 Swing Timer 并让它每 xxx 毫秒更新一次 Timer 显示,其中 xxx 将取决于您希望更新发生的频率。
  • Timer 将使用 ActionListener 就像您的 JButton 当前所做的那样。
  • 如果需要,您可以在 JButton 的 ActionListener 中启动 Timer,只需start()从 JButton 的 ActionListener 中调用 Timer。
  • 如果这是我的代码,我会让我的 DateFormat 对象成为一个字段并且只创建一次。我认为代码可以简化一些。
  • 这是Swing Timer 教程的链接。
于 2013-11-10T00:00:08.940 回答