# 动态时间显示到窗口
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ClockApp extends JFrame {
private JLabel timeLabel;
public ClockApp() {
setTitle("实时时钟");
setSize(200, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel();
// 初始显示时间
updateTime();
// 创建定时器,每秒刷新时间
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTime();
}
});
timer.start();
add(timeLabel);
setLocationRelativeTo(null);
setVisible(true);
}
// 更新时间标签
private void updateTime() {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedTime = now.format(formatter);
timeLabel.setText("时间:" + formattedTime);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new ClockApp();
});
}
}