1

I have a small game where I need to pause the timer when the user press Pause button and after to resume the timer and to continue to increase the seconds when the user press the Resume button. I researched a lot and I tried different solutions but none worked for me. Can you please help me to achieve this functionality ? Here is my code:

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

Thanks for reading this.

WJS
  • 36,363
  • 4
  • 24
  • 39
Florentin Lupascu
  • 754
  • 11
  • 30

2 Answers2

1

Try using a Swing timer.

    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
}

Then you can use stop() and start() methods to pause and resume action. Check the javaDocs for more details.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    Exactly what I was looking for ! But because is the first time when I touch Java I didn't know about this library ! Thank you very much !!! – Florentin Lupascu Mar 29 '21 at 14:13
0

Here is the full code for who will ever need something like this:

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

enter image description here

Florentin Lupascu
  • 754
  • 11
  • 30