简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM