How to know when a user has really released a key in Java?

前端 未结 10 1307
孤城傲影
孤城傲影 2020-11-30 11:09

(Edited for clarity)

I want to detect when a user presses and releases a key in Java Swing, ignoring the keyboard auto repeat feature. I also would like a pure Java

10条回答
  •  温柔的废话
    2020-11-30 12:00

    I've found a solution that does without waiting in case you have something like a game loop going. The idea is storing the release events. Then you can check against them both inside the game loop and inside the key pressed handler. By "(un)register a key" I mean the extracted true press/release events that should be processed by the application. Take care of synchronization when doing the following!

    • on release events: store the event per key; otherwise do nothing!
    • on press events: if there is no stored release event, this is a new press -> register it; if there is a stored event within 5 ms, this is an auto-repeat -> remove its release event; otherwise we have a stored release event that hasn't been cleared by the game loop, yet -> (fast user) do as you like, e.g. unregister-register
    • in your loop: check the stored release events and treat those that are older than 5 ms as true releases; unregister them; handle all registered keys

提交回复
热议问题