用Java写一个可以显示的时钟
以下是一个使用Java Swing库编写的时钟程序,可以在窗口中显示当前时间:
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class Clock extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel timeLabel;
public Clock() {
setTitle("Clock");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.PLAIN, 50));
add(timeLabel);
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTime();
}
});
timer.start();
}
private void updateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date now = new Date();
timeLabel.setText(sdf.format(now));
}
public static void main(String[] args) {
Clock clock = new Clock();
clock.setVisible(true);
}
}
该程序使用JFrame作为窗口,包含一个JLabel用于显示时间。使用Timer类每秒更新一次时间,使用SimpleDateFormat将当前时间格式化为字符串并在JLabel中显示。您可以根据需要自定义窗口大小和字体大小
原文地址: https://www.cveoy.top/t/topic/eGvz 著作权归作者所有。请勿转载和采集!