[英]Java is not picking up keypresses?
I have a program which produces a JFrame and then a JPanel on top of it. 我有一个程序,它生成一个JFrame,然后在其之上生成一个JPanel。 For the program, I have tried implementing the KeyListener and then adding the methods (for both components), but the program does not pick any of my key strokes up.
对于该程序,我尝试实现KeyListener,然后添加方法(针对两个组件),但是该程序未进行任何按键操作。 What am I doing wrong?
我究竟做错了什么?
EDIT 编辑
This is my code. 这是我的代码。 It is a part of the class which creates the JFrame.
它是创建JFrame的类的一部分。 It still does not pick up the press of the ESC key.
它仍然不按ESC键。
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_ESCAPE){
System.out.println("Hi");
}else{
System.out.println("Hello");
}
}
@Override
public void keyReleased(KeyEvent e) {
}
Without your code, all I can tell you is that usually when people ask this they don't know that the interface KeyListener
contain three methods as Agusti-N states in their answer here : 没有您的代码,我只能告诉您的是,通常当人们问这个问题时,他们不知道接口
KeyListener
包含三种方法,因为它们在此处的答案都是Agusti-N状态:
void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)
If you use keyTyped
and you are using event.getKeyCode()
to check for the character entered, this will not work. 如果使用
keyTyped
并且正在使用event.getKeyCode()
检查输入的字符,则将无法使用。 You should use getKeyChar()
for keyTyped
and getKeyCode()
for keyPressed
and keyReleased
. 您应该将
getKeyChar()
用于keyTyped
并将getKeyCode()
用于keyPressed
和keyReleased
。 Otherwise you'll get null
. 否则,您将得到
null
。 You should only use this if you do not have any other alternative, in most cases you want to use Key Bindings . 仅在没有其他选择的情况下才应使用此选项,在大多数情况下,您想使用“ 键绑定” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.