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.
Advertisement
Answer
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.