Java KeyListener keyPressed方法触发太快 [英] Java KeyListener keyPressed method fires too fast

查看:114
本文介绍了Java KeyListener keyPressed方法触发太快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用java KeyListener 类,您知道如果按住某个键 keyPressed 将触发一个 KeyEvent ,然后大约半秒后将非常快速地多次触发相同的键。我想知道是否有办法让 KeyEvents 从射击过快。我希望他们能够以每500毫秒一次的恒定速率进行。

If you use the java KeyListener class you know that if you hold down a key keyPressed will fire one KeyEvent, and then about half a second later will fire the same key many times very very fast. I would like to know if there is a way to keep the KeyEvents from firing too fast. I would like them to be at a nice constant rate of about once every 500 ms.

推荐答案

你可以,但诀窍是不要减慢事件的触发速度,但要降低处理它们的速度:

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) {   }

};

这篇关于Java KeyListener keyPressed方法触发太快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆