Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6750489
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T12:48:46+00:00 2026-05-26T12:48:46+00:00

I have hit another wall. After getting my key input working, I have been

  • 0

I have hit another wall. After getting my key input working, I have been racking my brains for hours, i want to create a pause function, so that if the same key is pressed again the timertask stops running (i.e the game is paused)

JPanel component = (JPanel)frame.getContentPane();
    component.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "space");
    component.getActionMap().put("space", (new AbstractAction(){
        public void actionPerformed(ActionEvent e){

            Timer timer = new Timer();

            timer.scheduleAtFixedRate(new TimerTask(){
            public void run(){
                    grid.stepGame();
                }
            },250, 250);



        }}));


        }

The problem is i cant use a global boolean isRunning var and switch it each time the key is pressed because the timerTask method in a nested class (so the boolean isRunning would have to be declared final to be accessed…). Any ideas on how to detect if the key is pressed again or if the game is already running so i can pause/cancel my timerTask.

Many Thanks Sam

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T12:48:47+00:00Added an answer on May 26, 2026 at 12:48 pm

    Since this is a Swing game, you should be using a javax.swing.Timer or Swing Timer and not a java.util.Timer. By using a Swing Timer, you guarantee that the code being called intermittently is called on the EDT, a key issue for Swing apps, and it also has a stop method that pauses the Timer. You can also give your anonymous AbstractAction class a private boolean field to check if the key is being pressed for the first time or not.

    Also, kudos and 1+ for using Key Bindings instead of a KeyListener.

    e.g.,

      JPanel component = (JPanel) frame.getContentPane();
      component.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "space");
      component.getActionMap().put("space", (new AbstractAction() {
         private boolean firstPress = true;
         private int timerDelay = 250;
         private javax.swing.Timer keyTimer = new javax.swing.Timer(timerDelay , new ActionListener() {
    
            // Swing Timer's actionPerformed
            public void actionPerformed(ActionEvent e) {
               grid.stepGame();
            }
         });
    
         // key binding AbstractAction's actionPerformed
         public void actionPerformed(ActionEvent e) {
            if (firstPress) {
               keyTimer.start();
            } else {
               keyTimer.stop();
            }
    
            firstPress = !firstPress;
         }
      }));
    

    Another useful option is to perform a repeating task on key press and stop it on key release, and this can be done easily by getting the keystrokes for on press and on release:

    KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true) // for key release
    KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false) // for key press
    

    For example:

    import java.awt.event.*;
    import javax.swing.*;
    
    public class SwingTimerEg2 {
       private JFrame frame;
       private Grid2 grid = new Grid2(this);
       private JTextArea textarea = new JTextArea(20, 20);
       private int stepCount = 0;
    
       public SwingTimerEg2() {
          frame = new JFrame();
    
          textarea.setEditable(false);
          frame.add(new JScrollPane(textarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
    
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
          setUpKeyBinding();
       }
    
       void setUpKeyBinding() {
          final int timerDelay = 250;
          final Timer keyTimer = new Timer(timerDelay, new ActionListener() {
    
             @Override
             public void actionPerformed(ActionEvent e) {
                grid.stepGame();
             }
          });
          JPanel component = (JPanel) frame.getContentPane();
          final int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
          final String spaceDown = "space down";
          final String spaceUp = "space up";
          component.getInputMap(condition).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false), spaceDown);
          component.getActionMap().put(spaceDown, (new AbstractAction() {
             public void actionPerformed(ActionEvent e) {
                keyTimer.start();
             }
          }));
          component.getInputMap(condition).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true), spaceUp);
          component.getActionMap().put(spaceUp, (new AbstractAction() {
             public void actionPerformed(ActionEvent e) {
                keyTimer.stop();
             }
          }));
    
       }
    
       public void doSomething() {
          textarea.append(String.format("Zap %d!!!%n", stepCount));
          stepCount ++;
       }
    
       private static void createAndShowGui() {
          new SwingTimerEg2();
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    
    }
    
    class Grid2 {
       private SwingTimerEg2 stEg;
    
       public Grid2(SwingTimerEg2 stEg) {
          this.stEg = stEg;
       }
    
       void stepGame() {
          stEg.doSomething();
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm working through Practical Web 2.0 Appications currently and have hit a bit of
I'm trying to do a cross domain POST request and have hit a wall
I've been getting several errors: cannot add an entity with a key that is
EDIT : I have another problem..Now I want to get the cookies value...in controllers
I'm working on a Chrome extension an I've hit a wall. function isInQueue(id) {
i've hit another brick wall today with jquery generated partialviews when located within areas.
I'm working on some code for a directed graph in NetworkX, and have hit
I have hit upon this problem about whether to use bignums in my language
I have hit a classic problem of needing to do a string replace on
I've seem to have hit a bug or i have overlooked something. I written

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.