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 3627566
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T23:54:17+00:00 2026-05-18T23:54:17+00:00

I have a program where the user can press a key to perform an

  • 0

I have a program where the user can press a key to perform an action. That one event takes a small amount of time. The user can also hold down that key and perform the action many times in a row. The issues is that the keyPress() events are queued up faster than the events can be processed. This means that after the user releases the key, events keep getting processed that were queued up from the user previously holding down the key. I also noticed that the keyRelease event doesn’t occur until after the final keyPress event is processed regardless of when the key was actually released. I’d like to be able to either
1. Detect the key release event and ignore future keyPress events until the user actually presses the key again.
2. Not perform a subsequent keyPress event until the first is one finished and then detect when the key is not pressed, and just stop.

Does anyone know how to do this?

  • 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-18T23:54:18+00:00Added an answer on May 18, 2026 at 11:54 pm

    Disclaimer: I am not feeling well so this code is horrific, as though.. it too is sick.

    What I want to happen: To access DirectInput to obtain a keyboard state, instead of events. That is far beyond the scope of this question though. So we will maintain our own action state.

    The problem you are having is that you are executing your action within the UI thread. You need to spawn a worker thread and ignore subsequent events until your action is completed.

    In the example I’ve given I start a new action when the letter ‘a’ is pressed or held down. It will not spawn another action until the first action has completed. The action updates a label on the form, displaying how many ‘cycles’ are left before it has completed.

    There is also another label that displays how many actions have occurred thus far.

    Spawning a new action

    The important part is to let all the UI key events to occur, not blocking in the UI thread causing them to queue up.

    public void keyPressed(KeyEvent e) {
        char keyChar = e.getKeyChar();
        System.out.println("KeyChar: " + keyChar);
        // Press a to start an Action
        if (keyChar == 'a') {
            if (!mAction.isRunning()) {
                mTotalActions.setText("Ran " + (++mTotalActionsRan) + " actions.");
                System.out.println("Starting new Action");
                Thread thread = new Thread(new Runnable() {
                    public void run() {
                        mAction.run();
                    }
                });
                thread.start();
            }
        }
    }
    

    Updates to the UI Thread

    If your action performs any kind of updates to the User Interface, it will need to use the SwingUtilities.invokeLater method. This method will queue your code to run in the UI thread. You cannot modify the user interface in a thread other than the UI thread. Also, only use SwingUtilities to update UI components. Any calculations, processing, etc that does not invoke methods on a Component, can be done outside the scope of SwingUtilities.invokeLater.

    Full Code Listing

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package stackoverflow_4589538;
    
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.Random;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    
    public class Main extends JFrame {
    
        private JLabel mActionLabel;
        private JLabel mTotalActions;
        private int mTotalActionsRan;
    
        private class MyAction {
    
            private boolean mIsRunning = false;
    
            public void run() {
                // Make up a random wait cycle time
                final int cycles = new Random().nextInt(100);
                for (int i = 0; i < cycles; ++i) {
                    final int currentCycle = i;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                    }
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                                mActionLabel.setText("Cycle " + currentCycle + " of " + cycles);
                        }
                    });
                }
                completed();
            }
    
            public synchronized void start() {
                mIsRunning = true;
            }
    
            public synchronized void completed() {
                mIsRunning = false;
            }
    
            public synchronized boolean isRunning() {
                return mIsRunning;
        }
    }
        private MyAction mAction = new MyAction();
    
        public Main() {
            setLayout(null);
            setBounds(40, 40, 800, 600);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            addKeyListener(new KeyAdapter() {
    
                @Override
                public void keyPressed(KeyEvent e) {
                    char keyChar = e.getKeyChar();
                    System.out.println("KeyChar: " + keyChar);
                    // Press A to start an Action
                    if (keyChar == 'a') {
                    if (!mAction.isRunning()) {
                            mTotalActions.setText("Ran " + (++mTotalActionsRan) + " actions.");
                            System.out.println("Starting new Action");
                            Thread thread = new Thread(new Runnable() {
    
                                public void run() {
                                    mAction.run();
                                }
                            });
                            // I had this within the run() method before
                            // but realized that it is possible for another UI event
                            // to occur and spawn another Action before, start() had
                            // occured within the thread
                            mAction.start();
                            thread.start();
                        }
                    }
                }
    
            @Override
                public void keyReleased(KeyEvent e) {
                }
            });
    
            mActionLabel = new JLabel();
            mActionLabel.setBounds(10, 10, 150, 40);
    
            mTotalActions = new JLabel();
            mTotalActions.setBounds(10, 50, 150, 40);
    
            add(mActionLabel);
            add(mTotalActions);
        }    
    
        public static void main(String[] args) {
            new Main().setVisible(true);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a program that creates a Windows user account using the NetUserAdd() API
I have a program that allows the user to enter a level number, and
I have a program that needs to run as a separate NT user to
I have a program that needs to run as a normal user most of
I have a single user java program that I would like to have store
I have a Win32 C++ program that validates user input and updates the UI
I have a console program and I want if the user press ctrl-z the
I have a program that stores user projects as databases. Naturally, the program should
I have a UIPickerView object that has five rows that a user can select.
I have a console program written in Java that should respond to single key

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.