Canvas子类没有接收KeyEvents

时间:2016-06-15 12:42:59

标签: java swing canvas event-handling

我有一个JFrame的子类,其中包含DrawingCanvas的实例(java.awt.Canvas的子类),我在KeyListener中实现了DrawingCanvas ,但它没有收到任何关键事件。

我还使用setFocusable()方法使画布可调焦,但我仍然无法接收重要事件。

DrawingCanvas.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) {
    }

    ...
    ...
}

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

您可能需要更改以下代码。

    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;
        }
    }

答案 1 :(得分:0)

正如@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);

        ...
    }

    ...
}