我有一个 JFrame
的子类,它使用从 JPanel
扩展的类
public class HelloWorld extends JPanel implements KeyListener
我将 HelloWorld
对象添加到框架 - app.add(helloWorld);
。现在,当我按下任何键盘键时,KeyListener
方法都不会被调用,并且 helloWorld
似乎没有窗口焦点。我也尝试调用 helloWorld.requestFocusInWindow();
但仍然没有响应。
如何让它响应按键?
最佳答案
您是否将 HelloWorld
面板的 KeyListener
设置为该面板本身?此外,您可能需要将该面板设置为可聚焦。我用这段代码测试了它,它似乎可以正常工作
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();
}
}
关于java - JPanel 不响应 KeyListener 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11487369/