Search code examples
javaswingkeylistenerkeyevent

KeyEvent not firing?


I have a class World as follows:

public class World extends JFrame implements KeyListener {
    public boolean left = false, right = false, back = false, fwd = false;

    public World() {
        this.setSize(600, 600);
        this.setVisible(true);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getExtendedKeyCode() == KeyEvent.VK_LEFT) left = true;
        if(e.getExtendedKeyCode() == KeyEvent.VK_RIGHT) right = true;
        if(e.getExtendedKeyCode() == KeyEvent.VK_UP) fwd= true;
        if(e.getExtendedKeyCode() == KeyEvent.VK_DOWN) back = true;
        System.out.println("L:"+left+" R:"+right+" F:"+fwd+" B:"+back);
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getExtendedKeyCode() == KeyEvent.VK_LEFT) left = false;
        if(e.getExtendedKeyCode() == KeyEvent.VK_RIGHT) right = false;
        if(e.getExtendedKeyCode() == KeyEvent.VK_UP) fwd= false;
        if(e.getExtendedKeyCode() == KeyEvent.VK_DOWN) back = false;
        System.out.println("L:"+left+" R:"+right+" F:"+fwd+" B:"+back);
    }

    @Override
    public void keyTyped(KeyEvent e) {}
}

This should, theoretically, trigger on key press or key release, however, it does not. Components in the frame are drawing properly.

The frame is being instantiated as follows:

World m = new World();
m.getContentPane().setBackground(Color.BLACK);

I can't seem to get the key listener to fire. There are no system outs. Any thoughts?


Solution

  • No, you're implementing the interface - but never telling anything that that's important.

    You could write this in your constructor:

    addKeyListener(this);
    

    ... that would do the right thing, I believe. Something has to add the keylistener, basically. Just implementing the interface doesn't automatically make anything start using that implementation.