在窗體中顯示倒計時的方法可以使用Java的Swing GUI庫來實現。具體步驟如下:
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));
}
}
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);
}
}
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。