下面是一个简单的Java时钟实现,使用了Java Swing和线程。
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.*;
public class MyClock extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel timeLabel;
public MyClock() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("时钟");
setSize(300, 100);
setLocationRelativeTo(null);
setResizable(false);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
timeLabel = new JLabel("", JLabel.CENTER);
timeLabel.setFont(new Font("Arial", Font.PLAIN, 24));
panel.add(timeLabel);
setContentPane(panel);
Thread clockThread = new Thread(() -> {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
while (true) {
Calendar cal = Calendar.getInstance();
String timeStr = sdf.format(cal.getTime());
SwingUtilities.invokeLater(() -> timeLabel.setText(timeStr));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
clockThread.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MyClock clock = new MyClock();
clock.setVisible(true);
});
}
}
这个时钟程序使用了Java Swing图形用户界面工具包来创建GUI界面,通过继承JFrame类并添加一个JLabel标签来显示时间。程序还创建了一个新线程来不断更新时间标签上的时间信息。在while循环中,程序先获取当前时间Calendar对象,然后使用SimpleDateFormat将其格式化为"HH:mm:ss"字符串格式,最后通过SwingUtilities.invokeLater更新标签的文本内容。程序在更新完文本内容后,通过Thread.sleep方法让线程休眠1秒钟,然后再继续执行循环。
注意,在实际应用中,需要考虑时钟的精度和误差处理等问题。