以下是一个Java多线程程序,每隔1秒在图形界面的文本框中刷新显示当前的系统时间:

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeDisplay extends JFrame implements Runnable {
    private JTextField textField;

    public TimeDisplay() {
        super("Time Display");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 100);
        setLocationRelativeTo(null);

        textField = new JTextField();
        textField.setEditable(false);
        textField.setFont(new Font("Arial", Font.PLAIN, 20));
        add(textField, BorderLayout.CENTER);

        setVisible(true);
    }

    @Override
    public void run() {
        while (true) {
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = dateFormat.format(now);
            textField.setText(time);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TimeDisplay timeDisplay = new TimeDisplay();
        Thread thread = new Thread(timeDisplay);
        thread.start();
    }
}

该程序继承了JFrame类,创建了一个窗口,其中包含一个文本框用于显示时间。在run方法中,通过SimpleDateFormat类获取当前时间并格式化,然后将其显示在文本框中。程序通过在main方法中启动一个新线程来实现每隔1秒刷新时间的功能

Java编写一个多线程的程序要求每隔1秒在图形界面的文本框中刷新显示当前的系统时间。

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

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