Java

java线程怎么在窗体中显示倒计时

小亿
86
2023-12-16 12:55:43
栏目: 编程语言

在窗体中显示倒计时的方法可以使用Java的Swing GUI库来实现。具体步骤如下:

  1. 创建一个继承自JFrame的窗体类CountdownFrame
import javax.swing.*;

public class CountdownFrame extends JFrame {
    private JLabel countdownLabel;

    public CountdownFrame() {
        countdownLabel = new JLabel();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("倒计时");
        setSize(200, 100);
        setLocationRelativeTo(null);
        setResizable(false);

        getContentPane().add(countdownLabel);

        setVisible(true);
    }

    public void setCountdown(int seconds) {
        countdownLabel.setText(String.valueOf(seconds));
    }
}
  1. 创建一个继承自Thread的线程类CountdownThread,用于倒计时并更新窗体上的显示。
public class CountdownThread extends Thread {
    private CountdownFrame frame;
    private int seconds;

    public CountdownThread(CountdownFrame frame, int seconds) {
        this.frame = frame;
        this.seconds = seconds;
    }

    @Override
    public void run() {
        while (seconds > 0) {
            frame.setCountdown(seconds);
            seconds--;

            try {
                Thread.sleep(1000); // 线程休眠1秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        frame.setCountdown(0);
    }
}
  1. 在主方法中创建CountdownFrame对象和CountdownThread对象,然后启动线程。
public class Main {
    public static void main(String[] args) {
        CountdownFrame frame = new CountdownFrame();
        CountdownThread thread = new CountdownThread(frame, 10);

        thread.start();
    }
}

以上代码会创建一个窗体,然后在窗体上显示从10开始的倒计时,每秒更新一次显示的数字,直到倒计时为0。

0
看了该问题的人还看了