Java KeyListener keyPressed method fires too fast

假装没事ソ 提交于 2019-11-28 12:53:51

You can, but the trick is to not slow down the firing of events, but to slow down how fast you process them:

KeyListener kl = new KeyListener() {
    private long lastPressProcessed = 0;

    @Override
    public void keyPressed(KeyEvent e) {
        if(System.currentTimeMillis() - lastPressProcessed > 500) {
            //Do your work here...
            lastPressProcessed = System.currentTimeMillis();
        }           
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyReleased(KeyEvent e) {   }

};

No, this is completely system dependent. You would have to listen for keyPressed events, start a timer on your own that fires events at a fixed rate and stop it at the next keyReleased event.

Try something like this:

component.addKeyListener(new KeyListener() {

    Timer t = new Timer();
    TimerTask tt;

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        tt.cancel();
        tt = null;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (tt != null)
            return;

        tt = new TimerTask() {
            @Override
            public void run() {
                System.out.println(System.currentTimeMillis() % 1000);
            }
        };

        t.scheduleAtFixedRate(tt, 0, 500);
    }
});

This is controlled by your OS. But you could easily have your handler check how long it is since the last time it fired and respond accordingly.

Usually the auto-repeat rate for keys is set by the system; I don't know if it's changeable from within Java. However, you can use the event arrival time to not react to one until 500ms after the last time you reacted (or after a key release, which should clear the timer for users who type fast).

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