java - 如何在 Java 中暂停和恢复计时器
问题描述
我有一个小游戏,当用户按下暂停按钮时我需要暂停计时器,然后恢复计时器并在用户按下恢复按钮时继续增加秒数。我进行了很多研究,并尝试了不同的解决方案,但没有一个对我有用。你能帮我实现这个功能吗?这是我的代码:
public class App {
private JTextField timerHours;
private JTextField timerMinutes;
private JTextField timerSeconds;
private Timer timer = new Timer();
private long timeElapsedInSeconds = 0;
private JButton playButton;
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
App window = new App();
} catch (Exception e) {
e.printStackTrace();
}
});
}
private App() {
initializeWindow();
createTimer();
}
private void createTimer() {
timer.schedule(new TimerTask() {
@Override
public void run() {
timeElapsedInSeconds += 1;
System.out.println("Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String.valueOf((timeElapsedInSeconds / 60) / 60));
}
}, 1000, 1000);
}
private void initializeWindow() {
JPanel bottom_panel = new JPanel();
bottom_panel.setLayout(null);
// Create Pause button
JButton pauseButton = new JButton("Pause");
pauseButton.setBounds(10, 20, 90, 25);
pauseButton.addActionListener(actionEvent -> {
// Pause the game
timer.cancel();
playButton.setEnabled(true);
pauseButton.setEnabled(false);
});
bottom_panel.add(pauseButton);
// Create Play button
playButton = new JButton("Play");
playButton.setBounds(110, 20, 90, 25);
playButton.setEnabled(false);
playButton.addActionListener(actionEvent -> {
// Resume the game and continue the timer from the value saved in `timeElapsedInSeconds`
playButton.setEnabled(false);
pauseButton.setEnabled(true);
});
bottom_panel.add(playButton);
}
感谢您阅读本文。
解决方案
尝试使用Swing 计时器。
private void createTimer() {
timer = new Timer(1000, (ae)->
{
timeElapsedInSeconds += 1;
System.out.println(
"Elapsed seconds: " + timeElapsedInSeconds);
timerSeconds.setText(
String.valueOf(timeElapsedInSeconds % 60));
timerMinutes.setText(String
.valueOf((timeElapsedInSeconds / 60) % 60));
timerHours.setText(String
.valueOf((timeElapsedInSeconds / 60) / 60));
});
timer.setDelay(1000);
timer.start(); // or start it elsewhere
}
然后你可以使用stop()
和start()
方法来暂停和恢复动作。检查 javaDocs 以获取更多详细信息。
推荐阅读
- java - ActiveMQ 5.9 - 由于未释放锁定,代理上的阻塞线程
- javascript - 无法在 Angular 6 中添加 Bootstrap 4
- pdf - pdftk - 使用 FDF 填写自动填写 PDF 表单
- spring - 实现简单 REST 服务的问题 - Spring MVC
- python - Python - 正则表达式匹配多行中的多个模式
- swift - 你将如何在 Swift 中发送重复的 HTTP 请求?
- wix - 如何将 WIX Bundle(EXE 文件)强制转换为特定语言
- r - 提取分布族的密度函数
- idris - 证明 `weaken` 不会改变数字的值
- r - 排除变量及其附近的变量- r dplyr