Java Countdown Timer with Popup: Code Tutorial

You can implement the code to display a pop-up window after a countdown in Java using the JOptionPane class in Swing. Here is an example code:

import javax.swing.JOptionPane;

public class CountdownPopup {
    public static void main(String[] args) {
        int countdownSeconds = 10; // 倒计时秒数
        Countdown countdown = new Countdown(countdownSeconds);
        countdown.start();
    }
    
    static class Countdown extends Thread {
        private int seconds;

        public Countdown(int seconds) {
            this.seconds = seconds;
        }

        @Override
        public void run() {
            try {
                while (seconds > 0) {
                    Thread.sleep(1000); // 每隔1秒减少1秒
                    seconds--;
                }
                // 倒计时结束,弹出弹窗
                JOptionPane.showMessageDialog(null, "倒计时结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

In this code, the countdown thread is implemented by inheriting the Thread class. Within the run method, the Thread.sleep method is used to decrease by one second every second until the countdown is finished. After the countdown ends, a dialog box containing a message text is displayed using the JOptionPane.showMessageDialog method. You can modify the countdown seconds and the content of the dialog box as needed.

bannerAds