App下載

使用Java線程實(shí)現(xiàn)時(shí)間動(dòng)態(tài)顯示 附具體代碼

猿友 2021-07-21 11:11:14 瀏覽數(shù) (2071)
反饋

本篇文章將通過(guò)具體的代碼實(shí)例,為大家展示如何通過(guò) Java 線程來(lái)實(shí)現(xiàn)時(shí)間動(dòng)態(tài)顯示的功能,以下是詳細(xì)內(nèi)容,供大家參考。

代碼如下:

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


public class Test1 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("我的窗口");
        frame.setBounds(200,200,400,400);
        JTextField textField=new JTextField();
        frame.add(textField);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Date date=new Date();
                    textField.setText(date.getHours()+":"+date.getMinutes()+":"+date.getSeconds());
                    textField.setFont(new Font("楷體",Font.BOLD,20));
                }
            }
        }).start();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

運(yùn)行結(jié)果:

以上就是關(guān)于使用Java線程實(shí)現(xiàn)時(shí)間動(dòng)態(tài)顯示及具體實(shí)例代碼的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持W3Cschool。


0 人點(diǎn)贊