KeyListener,keyPressed与keyTyped [英] KeyListener, keyPressed versus keyTyped

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

问题描述

我有一个JFrame(好吧,一个扩展JFrame的类),我想在按F5键时执行操作。所以,我让类实现了KeyListener。有了它,有三个方法,keyPressed,keyReleased和keyTyped。

I have a JFrame (well, a class which extends JFrame) and I want to do an action when I press the F5 key. So, I made the class implement KeyListener. And with that, came three methods, keyPressed, keyReleased, and keyTyped.

我应该使用哪些方法来监听F5被按下? keyPressed或keyTyped?我目前有以下内容,但是当我按下F5时它不会打印任何内容。

Which of these methods should I use to listen for F5 being pressed? keyPressed or keyTyped? I currently have the following, however it does not print anything when I press F5.

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_F5)
        System.out.println("F5 pressed");
}

public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub

}

public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub

}


推荐答案

keyPressed - when the key goes down
keyReleased - when the key comes up
keyTyped - when the unicode character represented by this key is sent by the keyboard to system input.

我个人会为此使用keyReleased。只有当他们举起手指时才会开火。

I personally would use keyReleased for this. It will fire only when they lift their finger up.

请注意,keyTyped仅适用于可以打印的东西(我不知道F5是否可以)如果关键被按下,我相信会一遍又一遍地开火。这对于诸如......在屏幕上移动角色等内容非常有用。

Note that keyTyped will only work for something that can be printed (I don't know if F5 can or not) and I believe will fire over and over again if the key is held down. This would be useful for something like... moving a character across the screen or something.

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

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