溫馨提示×

如何自定義Java倒計(jì)時器的樣式

小樊
82
2024-09-03 15:01:05
欄目: 編程語言

要自定義Java倒計(jì)時器的樣式,您可以使用Java Swing庫中的組件和布局

  1. 首先,導(dǎo)入所需的庫:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
  1. 創(chuàng)建一個自定義的JPanel類,用于顯示倒計(jì)時器:
class CountdownTimerPanel extends JPanel {
    private int countdownSeconds;
    private Timer timer;
    private JLabel timeLabel;

    public CountdownTimerPanel(int countdownSeconds) {
        this.countdownSeconds = countdownSeconds;
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(200, 100));
        setBackground(Color.WHITE);

        timeLabel = new JLabel(String.valueOf(countdownSeconds), SwingConstants.CENTER);
        timeLabel.setFont(new Font("Arial", Font.BOLD, 48));
        add(timeLabel);

        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                countdownSeconds--;
                if (countdownSeconds < 0) {
                    timer.stop();
                    return;
                }
                timeLabel.setText(String.valueOf(countdownSeconds));
            }
        });
    }

    public void startCountdown() {
        timer.start();
    }
}
  1. 在主類中創(chuàng)建一個JFrame并添加自定義的CountdownTimerPanel:
public class CustomCountdownTimer {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Custom Countdown Timer");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            CountdownTimerPanel countdownTimerPanel = new CountdownTimerPanel(10);
            frame.add(countdownTimerPanel);

            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            countdownTimerPanel.startCountdown();
        });
    }
}

這個例子展示了一個簡單的倒計(jì)時器,它會從指定的秒數(shù)開始倒計(jì)時。您可以根據(jù)需要修改CountdownTimerPanel類以自定義外觀和行為。例如,您可以更改字體、顏色、背景等。

0