以下是使用Java Swing框架编写的简单钟表示例代码:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Clock extends JPanel implements Runnable {

    private static final long serialVersionUID = 1L;

    private Thread thread = null;

    public Clock() {
        setBackground(Color.BLACK);
        setSize(300, 300);
        thread = new Thread(this);
        thread.start();
    }

    public void run() {
        while (true) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void paint(Graphics g) {
        super.paint(g);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat('hh:mm:ss');
        String time = dateFormat.format(calendar.getTime());

        g.setColor(Color.GREEN);
        g.setFont(new Font('Arial', Font.BOLD, 40));
        g.drawString(time, 80, 150);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame('Clock');
        frame.getContentPane().add(new Clock());
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

该程序使用Java Swing框架创建一个简单的窗口,并在其上绘制一个时钟。程序使用线程来更新时钟的时间,并在每秒钟重绘时钟。时钟使用当前时间,并在窗口的中心位置以绿色显示。

Java Swing 实现简单时钟:代码示例与解析

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

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