更多文章:如何用Java GUI开发一个时钟 (techdatafuture.com)
以下是一个用Java GUI开发一个时钟的示例代码:
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Clock extends JFrame {
private JLabel timeLabel;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Clock clock = new Clock();
clock.setVisible(true);
});
}
public Clock() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Clock");
setSize(300, 200);
setLocationRelativeTo(null);
timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.BOLD, 40));
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
updateTime();
Timer timer = new Timer(1000, e -> updateTime());
timer.start();
getContentPane().add(timeLabel);
}
private void updateTime() {
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String timeText = dateFormat.format(currentTime);
timeLabel.setText(timeText);
}
}
这个示例代码创建了一个继承自`JFrame`的`Clock`类。在构造函数中,设置了窗口的一些基本属性,并创建了一个`JLabel`来显示时间。然后,使用`Timer`类每隔一秒更新时间。`updateTime()`方法使用`SimpleDateFormat`将当前时间格式化为"HH:mm:ss"的字符串,然后将其设置为`timeLabel`的文本。最后,将`timeLabel`添加到窗口的内容面板中。
要编译和运行这个代码,你需要安装Java开发工具包(Java Development Kit,JDK),并将代码保存为一个名为`Clock.java`的文件。然后,在命令行窗口中使用`javac Clock.java`编译代码,再使用`java Clock`运行程序。
更多文章:技数未来