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

前端 未结 10 1354
孤城傲影
孤城傲影 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 11:47

    This question is duplicated here.

    In that question, a link to the Sun bug parade is given, where some workaround is suggested.

    I've made a hack implemented as an AWTEventListener that can be installed at the start of the application.

    Basically, observe that the time between the RELEASED and the subsequent PRESSED is small - actually, it is 0 millis. Thus, you can use that as a measure: Hold the RELEASED for some time, and if a new PRESSED comes right after, then swallow the RELEASED and just handle the PRESSED (And thus you will get the same logic as on Windows, which obviously is the correct way). However, watch for the wrap-over from one millisecond to the next (I've seen this happen) - so use at least 1 ms to check. To account for lags and whatnots, some 20-30 milliseconds probably won't hurt.

提交回复
热议问题