cyberpirate92
cyberpirate92

Reputation: 3176

Canvas subclass not receiving KeyEvents

I have a subclass of JFrame, which contains an instance of DrawingCanvas ( a subclass of java.awt.Canvas), I have a KeyListener implemented in DrawingCanvas, but it's not receiving any key events.

I have also made the canvas focusable using the setFocusable() method, but still I'm unable to receive key events.

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

    ...
    ...
}

What am I missing here?

Upvotes: 1

Views: 42

Answers (2)

Beniton Fernando
Beniton Fernando

Reputation: 1533

You may have to change your code like below.

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

Upvotes: 1

cyberpirate92
cyberpirate92

Reputation: 3176

As pointed out by @Jägermeister in the comments, I have indeed missed registering the KeyListener in the other class, adding that resolved my issue.

class DrawThreads extends JFrame implements ActionListener {

    ...

    public DrawThreads(int width, int height) {
        ...

        drawingCanvas = new DrawingCanvas();
        drawingCanvas.addKeyListener(drawingCanvas); // register listener
        drawingCanvas.setFocusable(true);

        ...
    }

    ...
}

Upvotes: 0

Related Questions