public TestClock() { this.setSize(1200, 1000); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(new GridLayout(2, 1)); Panel p1 = new Panel(new GridLayout(1, 3)); Calendar c = Calendar.getInstance(); hour = Integer.toString(c.get(Calendar.HOUR)); minute = Integer.toString(c.get(Calendar.MINUTE)); second = Integer.toString(c.get(Calendar.SECOND)); aorp = Integer.toString(c.get(Calendar.AM_PM)); JLabel HH = new JLabel(hour, SwingConstants.CENTER); JLabel MM = new JLabel(minute, SwingConstants.CENTER); JLabel SS = new JLabel(second, SwingConstants.CENTER); JLabel AorP = new JLabel(aorp, SwingConstants.CENTER); HH.setFont(new Font(Font.SERIF, Font.ITALIC, 36)); MM.setFont(new Font(Font.SERIF, Font.ITALIC, 36)); SS.setFont(new Font(Font.SERIF, Font.ITALIC, 36)); AorP.setFont(new Font(Font.SERIF, Font.ITALIC, 26)); p1.add(HH); p1.add(MM); p1.add(SS); this.add(p1); this.add(AorP); }能实时更新时间吗
时间: 2024-02-11 13:07:33 浏览: 20
这段代码可以在程序启动时显示当前时间,但它不能实时更新时间。要实现实时更新时间,您需要使用定时器(Timer)类或线程(Thread)来定期更新标签文本。
您可以在TestClock构造函数中添加一个计时器来定期更新标签文本。例如,以下代码将每秒钟更新一次标签文本:
```
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Calendar c = Calendar.getInstance();
hour = Integer.toString(c.get(Calendar.HOUR));
minute = Integer.toString(c.get(Calendar.MINUTE));
second = Integer.toString(c.get(Calendar.SECOND));
aorp = Integer.toString(c.get(Calendar.AM_PM));
HH.setText(hour);
MM.setText(minute);
SS.setText(second);
AorP.setText(aorp);
}
});
timer.start();
```
这段代码创建了一个计时器,每秒钟触发一次 actionPerformed 方法,该方法会更新标签文本以反映当前时间。您需要将 HH、MM、SS 和 AorP 标签声明为 TestClock 类的成员变量,以便 actionPerformed 方法可以访问它们。