首页 > 解决方案 > 如何在 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);
}

感谢您阅读本文。

标签: javaswingtimer

解决方案


尝试使用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 以获取更多详细信息。


推荐阅读