import javax.swing.*;
import java.awt.*;
import java.time.LocalDateTime;
public class DigitalClock extends JFrame {
private JLabel clockLabel;
public Chatgpt_DigitalClock() {
super("Digital Clock");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // 弹窗居中
clockLabel = new JLabel();
clockLabel.setFont(new Font("Serif", Font.BOLD, 24));
clockLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel panel = new JPanel();
panel.add(clockLabel);
add(panel, BorderLayout.CENTER);
// 更新时间
new java.util.Timer().scheduleAtFixedRate(new java.util.TimerTask() {
@Override
public void run() {
updateClock();
}
}, 0, 1000); // 更新每一秒
setVisible(true);
}
private void updateClock() {
LocalDateTime now=LocalDateTime.now();
String sum="";
sum="当前时间:"+now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth() +" "+now.getHour()+":"+now.getMinute()+":"+ now.getSecond();
clockLabel.setText(sum);
}
public static void main(String[] args) {
new DigitalClock();
}
}
java实现当前时钟代码
于 2024-06-19 20:09:06 首次发布