JPanel不响应KeyListener事件 [英] JPanel doesn't response to KeyListener event
问题描述
我有一个 JFrame
的子类,它使用从 JPanel扩展的类
I have a subclass of JFrame
that uses a class extended from JPanel
public class HelloWorld extends JPanel implements KeyListener
我将 HelloWorld
的对象添加到框架 - app.add(helloWorld);
。现在,当我按下任何键盘键时, KeyListener
方法被调用,似乎 helloWorld
没有窗口焦点。我也试过调用 helloWorld.requestFocusInWindow();
但仍然没有回复。
I add an object of HelloWorld
to the frame - app.add(helloWorld);
. Now, when I press any keyboard key non of the KeyListener
methods gets called and it seems that helloWorld
doesn't have window focus. I have tried also to invoke helloWorld.requestFocusInWindow();
but still doesn't respond.
我怎么能让它回应按键?
How can I make it respond to key press?
推荐答案
你设置了 KeyListener
你的 HelloWorld
面板会是那个面板本身?此外,您可能需要将该面板设置为可聚焦。我通过这段代码对它进行了测试,它似乎工作正常,
Did you set that KeyListener
for your HelloWorld
panel would be that panel itself? Also you probably need to set that panel focusable. I tested it by this code and it seems to work as it should
class HelloWorld extends JPanel implements KeyListener{
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped: "+e);
}
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed: "+e);
}
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased: "+e);
}
}
class MyFrame extends JFrame {
public MyFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200,200);
HelloWorld helloWorld=new HelloWorld();
helloWorld.addKeyListener(helloWorld);
helloWorld.setFocusable(true);
add(helloWorld);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
这篇关于JPanel不响应KeyListener事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!