Java Countdown Timer GUI Tutorial

One way to create a countdown timer with a graphical interface in Java is by using Swing or JavaFX to build the interface. Here is an example code showing how to implement a countdown timer using Swing.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CountdownTimer extends JFrame {
    private JLabel timerLabel;
    private Timer timer;
    private int counter;

    public CountdownTimer(int seconds) {
        counter = seconds;
        timerLabel = new JLabel(String.valueOf(counter), SwingConstants.CENTER);
        timerLabel.setFont(new Font("Arial", Font.BOLD, 24));
        getContentPane().add(timerLabel, BorderLayout.CENTER);

        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                counter--;
                timerLabel.setText(String.valueOf(counter));
                if (counter == 0) {
                    timer.stop();
                    JOptionPane.showMessageDialog(CountdownTimer.this, "倒计时结束");
                }
            }
        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setVisible(true);

        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CountdownTimer(10));
    }
}

This example utilizes a JFrame as a window container and adds a JLabel to display the countdown value. It uses the Timer class to trigger an ActionEvent every second to update the countdown value and check if the countdown has ended. When the countdown ends, a message box pops up to notify the end of the countdown. You can modify the countdown seconds and the interface style as needed.

bannerAds