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

∥☆過路亽.° 提交于 2019-11-26 08:29:36

问题


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.


回答1:


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.




回答2:


This question is duplicated here.

Here's a hack implemented as an AWTEventListener that can be installed at the start of the application.




回答3:


Here's the bug from Sun (includes sample work-arounds): http://bugs.sun.com/view_bug.do?bug_id=4153069




回答4:


You can find a pretty good workaround here.




回答5:


Use the KeyEventDispatcher implementation, with it you'll make key binds correctly.



来源:https://stackoverflow.com/questions/1736828/how-to-stop-repeated-keypressed-keyreleased-events-in-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!