要自定義Java倒計時器的樣式,您可以使用Java Swing庫中的組件和布局
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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();
}
}
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();
});
}
}
這個例子展示了一個簡單的倒計時器,它會從指定的秒數開始倒計時。您可以根據需要修改CountdownTimerPanel類以自定義外觀和行為。例如,您可以更改字體、顏色、背景等。