这是一个基于Java Swing的倒计时器,可以自定义倒计时的时间长度。在界面中,有一个显示倒计时的标签和两个控制按钮(开始和停止)。在倒计时开始时,将启动一个Java计时器,并每秒调用“actionPerformed”方法,减少秒数并更新标签。如果倒计时结束,则弹出“时间到!”的对话框。可以通过调用“startTimer”和“stopTimer”方法来启动/停止计时器。
代码如下(示例):
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 seconds;
public CountdownTimer(int seconds) {
this.seconds = seconds;
timerLabel = new JLabel();
timerLabel.setFont(new Font("Arial", Font.BOLD, 24));
timerLabel.setHorizontalAlignment(SwingConstants.CENTER);
updateTimerLabel();
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startTimer();
}
});
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopTimer();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
setLayout(new BorderLayout());
add(timerLabel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setTitle("Countdown Timer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
}
private void startTimer() {
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
seconds--;
updateTimerLabel();
if (seconds<= 0) { // 倒计时结束的条件判断
stopTimer();
JOptionPane.showMessageDialog(null, "Time's up!");
}
}
});
timer.start();
}
private void stopTimer() {
if (timer != null) {
timer.stop();
}
}
private void updateTimerLabel() {
int displayMinutes = seconds / 60;
int displaySeconds = seconds % 60;
String timeStr = String.format("%02d:%02d", displayMinutes, displaySeconds);
timerLabel.setText(timeStr);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CountdownTimer(60); // 设置倒计时时间(单位:秒)
}
});
}
}