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

查看:31
本文介绍了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天全站免登陆