以下是一个简单的Java倒计时和秒表程序示例,其中使用了Timer和'计时器任务TimerTask类来实现计时功能,使用了'FileFile和'FileWriterFileWriter类来实现断电记忆功能。在程序中,倒计时可以通过设置'countDownSecondscountDownSeconds变量来设置,秒表可以通过点击"开始"和"停止"按钮来控制计时。每次停止计时后,程序将自动保存当前计时的时间戳,以实现断电记忆功能。
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class TimerExample extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel countDownLabel, stopWatchLabel;
private JButton countDownButton, stopWatchButton, stopButton;
private Timer countDownTimer, stopWatchTimer;
private int countDownSeconds, stopWatchSeconds;
private long lastStopWatchTime;
public TimerExample() {
super("倒计时和秒表");
setLayout(new GridLayout(3, 2, 10, 10));
// 倒计时标签和按钮
countDownLabel = new JLabel("倒计时: 00:00:00");
countDownButton = new JButton("开始倒计时");
countDownButton.addActionListener(this);
add(countDownLabel);
add(countDownButton);
// 秒表标签和按钮
stopWatchLabel = new JLabel("秒表: 00:00:00");
stopWatchButton = new JButton("开始");
stopWatchButton.addActionListener(this);
stopButton = new JButton("停止");
stopButton.addActionListener(this);
stopButton.setEnabled(false);
add(stopWatchLabel);
add(stopWatchButton);
add(stopButton);
// 初始化计时器
countDownTimer = new Timer(1000, new CountDownTask());
stopWatchTimer = new Timer(1000, new StopWatchTask());
// 恢复上一次停止的时间
try {
File file = new File("last_stopwatch_time.txt");
if (file.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(file));
lastStopWatchTime = Long.parseLong(reader.readLine());
reader.close();
stopWatchSeconds = (int) ((System.currentTimeMillis() - lastStopWatchTime) / 1000);
updateStopWatchLabel();
}
} catch (IOException e) {
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setVisible(true);
}
private void updateCountDownLabel() {
int hours = countDownSeconds / 3600;
int minutes = (countDownSeconds % 3600) / 60;
int seconds = countDownSeconds % 60;
countDownLabel.setText(String.format("倒计时: %02d:%02d:%02d", hours, minutes, seconds));
}
private void updateStopWatchLabel() {
int hours = stopWatchSeconds / 3600;
int minutes = (stopWatchSeconds % 3600) / 60;
int seconds = stopWatchSeconds % 60;
stopWatchLabel.setText(String.format("秒表: %02d:%02d:%02d", hours, minutes, seconds));
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == countDownButton) {
if (countDownTimer.isRunning())
温馨提示:答案为网友推荐,仅供参考