当前位置: 首页 > 知识库问答 >
问题:

如何在Java中暂停和重新计算计时器

巢安澜
2023-03-14

我有一个小游戏,当用户按下暂停按钮时,我需要暂停计时器,然后恢复计时器,并在用户按下恢复按钮时继续增加秒数。我研究了很多,我尝试了不同的解决方案,但没有一个对我有效。你能帮我实现这个功能吗?下面是我的代码:

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);
}

谢谢你读这篇文章。

共有2个答案

虞滨海
2023-03-14

以下是谁需要这样的东西的完整代码:

import javax.swing.*;
import java.awt.*;

public class App {
    private JFrame gameFrame;
    private JTextField timerHours;
    private JTextField timerMinutes;
    private JTextField timerSeconds;
    private Timer timer;
    private long timeElapsedInSeconds = 0;
    private JButton playButton;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                App window = new App();
                window.gameFrame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private App() {
        initializeWindow();
        createTimer();
    }

    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
    }

    private void initializeWindow() {

        // Create main window
        gameFrame = new JFrame();
        gameFrame.setFocusable(true);
        gameFrame.requestFocus();
        gameFrame.setFocusTraversalKeysEnabled(false);
        gameFrame.setTitle("My Game");
        gameFrame.setResizable(false);
        gameFrame.setBounds(100, 100, 700, 600);
        gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create right panel of main window which will contain the Digital Timer, Console buttons etc
        JPanel right_panel = new JPanel();
        right_panel.setLayout(null);

        // Create bottom panel of main window which will contain the buttons
        JPanel bottom_panel = new JPanel();
        bottom_panel.setLayout(null);

        // Create Digital Timer
        JPanel digital_timer = new JPanel();
        digital_timer.setLayout(new FlowLayout());
        digital_timer.setBounds(30, 10, 100, 60);
        JLabel timer_label = new JLabel("DIGITAL TIMER");
        timer_label.setForeground(Color.black);
        digital_timer.add(timer_label);

        // Create hours textField for digital timer
        timerHours = new JTextField("00");
        timerHours.setEditable(false);
        timerHours.setBackground(Color.black);
        timerHours.setForeground(Color.white);
        digital_timer.add(timerHours);

        JLabel timer_label2 = new JLabel(":");
        timer_label2.setForeground(Color.white);
        digital_timer.add(timer_label2);

        // Create minutes textField for digital timer
        timerMinutes = new JTextField("00");
        timerMinutes.setEditable(false);
        timerMinutes.setBackground(Color.black);
        timerMinutes.setForeground(Color.white);
        digital_timer.add(timerMinutes);

        JLabel timer_label3 = new JLabel(":");
        timer_label3.setForeground(Color.white);
        digital_timer.add(timer_label3);

        // Create seconds textField for digital timer
        timerSeconds = new JTextField("00");
        timerSeconds.setEditable(false);
        timerSeconds.setBackground(Color.black);
        timerSeconds.setForeground(Color.white);
        digital_timer.add(timerSeconds);

        right_panel.add(digital_timer);

        // Create Pause button
        JButton pauseButton = new JButton("Pause");
        pauseButton.setBounds(10, 20, 90, 25);
        pauseButton.addActionListener(actionEvent -> {
            // Pause the game
            timer.stop();
            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 -> {
            // Run the game
            timer.start();
            playButton.setEnabled(false);
            pauseButton.setEnabled(true);
        });
        bottom_panel.add(playButton);

        // Create a group of layouts (Container) where to put all frames and panels used in this app.
        GroupLayout groupLayout = new GroupLayout(gameFrame.getContentPane());
        groupLayout.setHorizontalGroup(
                groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                // Set width dimensions for right panel
                                .addComponent(right_panel, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE))
                        // Set width dimensions for bottom panel
                        .addComponent(bottom_panel, GroupLayout.PREFERRED_SIZE, 650, GroupLayout.PREFERRED_SIZE)
        );
        groupLayout.setVerticalGroup(
                groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGroup(groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                        //  Set height dimensions for right panel
                                        .addComponent(right_panel, GroupLayout.PREFERRED_SIZE, 500, GroupLayout.PREFERRED_SIZE))
                                // Set height dimensions for bottom panel
                                .addComponent(bottom_panel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        gameFrame.getContentPane().setLayout(groupLayout);
    }
}
漆雕稳
2023-03-14

尝试使用摆动计时器。

    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获得更多详细信息。

 类似资料:
  • 问题内容: 我已经开发了一个倒数计时器,但不确定单击计时器的文本视图时如何暂停和恢复计时器。单击开始,然后再次单击以暂停并继续,再次单击计时器的文本视图。 这是我的代码: 问题答案: 资料来源:本要点。

  • 问题内容: 我想从19:00:00中减去两个时间段,例如16:00:00。是否有任何Java函数?结果可以是毫秒,秒或分钟。 问题答案: 差异以毫秒为单位。

  • 有没有一种方法可以暂停Dataproc群集,这样当我不积极运行火花外壳或火花提交作业时就不会收到账单?此链接处的群集管理说明:https://cloud.google.com/sdk/gcloud/reference/beta/dataproc/clusters/ 仅演示如何销毁群集,但我安装了spark cassandra连接器API。这是我创建每次都需要安装的映像的唯一选择吗?

  • 问题内容: 如果用户输入为2255,而我的输出应为10分钟,那么我如何计算24小时内的时差。我的想法是将输入分为2个部分,2位数字和2位数字。前2位数字是小时,将其乘以60使其变为分钟。然后再加上第二个2位数字,然后计算出差异。我不想使用任何日期日历数据类型或API来解决它。谢谢 问题答案: 如何在不使用String chartAt的情况下获取前两位数字。 最高两位数:数字/ 100最低两位数:数

  • 我尝试创建一个自定义的时间流逝时间,一旦我按住音量键,它就会启动计时器,并假设时间必须在我松开键后停止,但我松开键时遇到问题,计时器仍在移动。请告诉我我错过了什么谢谢 公共布尔onKeyDown(int-keyCode,KeyEvent-event){if((keyCode==KeyEvent.keyCode_-VOLUME_-DOWN

  • 基本上,我想做的是制作一个计时器,在x秒后运行一个特定的TimerTask,但是TimerTask可以重新安排计时器在y秒后执行任务。下面是一个示例,它在我试图在TimerTask run中调度此任务的行上给出了一个错误“线程中的异常”Timer-0“java.lang.IllegalStateException:任务已调度或已取消”。