Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop repeated keyPressed() / keyReleased() events in Swing

So the problem that I am having appears to be a bug that occurs only on Linux. I'm trying to have my swing app record when a key is pressed down, then to detect when that key is released. Now that shouldn't be in issue because KeyListener is supposed to handle this for me.

The problem is that when I hold the key down I get lots of repeated keyPressed()/keyReleased() events instead of just the single keypressed(). Does anyone have a solution or workaround for knowing when a key is really released on linux?

Thank you.

like image 682
Sandro Avatar asked Nov 15 '09 06:11

Sandro


People also ask

What is the difference between keyTyped and keyPressed?

The keyPressed method is called when the user presses a key, the keyReleased method is called when the user releases a key, and the keyTyped method is called when the user types a character.

What is the purpose of KeyListener?

Interface KeyListenerA keyboard event is generated when a key is pressed, released, or typed. The relevant method in the listener object is then invoked, and the KeyEvent is passed to it.

What is keypress event in Java?

An event which indicates that a keystroke occurred in a component. This low-level event is generated by a component object (such as a text field) when a key is pressed, released, or typed.


1 Answers

So the problem that I am having appears to be a bug that occurs only on Linux

Yes this is a Linux problem.

On Windows when a key is held down you get multiple KeyPressed events but only a single KeyReleased event.

This question is asked often and I've never seen a good solution.

But I think the basis of a solution is to use a Timer. When the key is pressed you start a Timer. When you get another keyPressed you restart the Timer. So as long as the Timer interval is greater than the repeat rate of the key board the Timer will be continually reset when a key is held down. When keyPresses stop being generated the Timer will fire so you assume the key has been released. This implies you will have a delay in processing the keyReleased.

like image 102
camickr Avatar answered Sep 20 '22 17:09

camickr