tckmn
tckmn

Reputation: 59273

KeyListener not adding

I am pretty sure I am missing something pretty simple here, but I just can't find it!

Here is the declaration for my GamePanel class:

private class GamePanel extends JPanel implements KeyListener {

In its constructor is:

addKeyListener(this);

Also in the constructor:

        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    index ++;
                    index = index >= 15 ? 0 : index;
                    if (aPress) {
                        playerX --;
                    }
                    if (dPress) {
                        playerX ++;
                    }
                    repaint();
                    try {
                        Thread.sleep(25);
                    } catch (InterruptedException e) {}
                }
            }

        }).start();

In the class:

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("Key pressed!");
        if (e.getKeyCode() == KeyEvent.VK_A) {
            aPress = true;
        }
        if (e.getKeyCode() == KeyEvent.VK_D) {
            dPress = true;
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_A) {
            aPress = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_D) {
            dPress = false;
        }
    }

And finally:

JFrame f = new JFrame();
//set up f
f.add(new GamePanel());
f.setVisible(true);

I even added a System.out.println in my keyPressed method and it won't print! What am I missing?

Upvotes: 0

Views: 153

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

KeyListener is a fickle mistress. The component where the KeyListener is registered must be focusable and must have focus in order for it to receive key events.

Try adding setFocusable(true); and requestFocusInWindow(); after you have registered the listener.

A better idea would be to use key bindings, this will over come the focus issue.

InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "a.pressed");
am.put("a.pressed", new AbstractAction() {
    public void actionPerformed(ActionEvent evt) {
        aPress = true;
    }
});

Upvotes: 5

Ryan
Ryan

Reputation: 672

Add setFocusable(true); to the GamePanel constructor.

Upvotes: 2

Related Questions