我试图在您单击按钮时在文本字段上显示实际的系统时间。到目前为止,如果您每次单击按钮,它只会显示实时结果。我正在努力附加 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()));
}
最佳答案
感谢您对问题的修改。
- 要让时间不断 self 更新,请使用 Swing 计时器并让它每 xxx 毫秒更新一次计时器显示,其中 xxx 将取决于您希望更新的频率。
- Timer 会像您的 JButton 当前那样使用 ActionListener。
- 如果需要,您可以在 JButton 的 ActionListener 中启动 Timer,只需从 JButton 的 ActionListener 中调用 Timer 上的
start()
即可。 - 如果这是我的代码,我会将我的 DateFormat 对象设为一个字段,并且只创建一次。我认为代码可以简化一些。
- 这是一个指向 Swing Timer Tutorial 的链接.
关于java - 如何给这个按钮添加 Action 监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19884652/