以下是一个使用 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 中显示。您可以根据需要自定义窗口大小和字体大小。

Java Swing 实时时钟程序 - 代码示例

原文地址: https://www.cveoy.top/t/topic/nXiJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录