在窗体中显示倒计时的方法可以使用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。