user1131435
user1131435

Reputation:

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?

Upvotes: 2

Views: 5469

Answers (2)

Reimeus
Reimeus

Reputation: 159754

Apart from not adding the KeyListener, JFrame is not focusable by default so does not send KeyEvents to the window - KeyEvents themselves require focus to work. For this reason, the preferred way to interact with KeyStrokes in Swing is to use Key Bindings which work without component focus.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 6

Related Questions