我有一个JFrame
的子类,其中包含一个DrawingCanvas
的实例(java.awt.Canvas
的子类),我在DrawingCanvas
中实现了KeyListener
,但它没有收到任何关键事件。
我还使用setFocusable()
方法使Canvas可以集中注意力,但是我仍然无法接收关键事件。
drawdcanvas.java
class DrawingCanvas extends Canvas implements TimePulseListener, KeyListener {
...
...
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_KP_DOWN:
case KeyEvent.VK_KP_UP:
xFlag = false;
yFlag = true;
reverseY();
break;
case KeyEvent.VK_KP_LEFT:
case KeyEvent.VK_KP_RIGHT:
xFlag = true;
yFlag = false;
reverseX();
break;
default:
System.out.println(" * NOT an action key ");
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
...
...
}
我在这里缺少什么?
您可能必须像下面更改代码。
public DrawingCanvas() {
super();
this.addKeyListener(this);
}
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_DOWN:
case KeyEvent.VK_KP_DOWN:
case KeyEvent.VK_UP:
case KeyEvent.VK_KP_UP:
xFlag = false;
yFlag = true;
reverseY();
break;
case KeyEvent.VK_LEFT:
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_KP_LEFT:
case KeyEvent.VK_KP_RIGHT:
xFlag = true;
yFlag = false;
reverseX();
break;
default:
System.out.println(" * NOT an action key " + e.getKeyChar());
break;
}
}
正如 @jägermeister在评论中指出的那样,我确实错过了在另一类中注册KeyListener
,并补充了解决我的问题。
class DrawThreads extends JFrame implements ActionListener {
...
public DrawThreads(int width, int height) {
...
drawingCanvas = new DrawingCanvas();
drawingCanvas.addKeyListener(drawingCanvas); // register listener
drawingCanvas.setFocusable(true);
...
}
...
}