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?
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.
Updates to the UI Thread
If your action performs any kind of updates to the User Interface, it will need to use the
SwingUtilities.invokeLatermethod. 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