Blaise
Blaise

Reputation: 106

Why is my KeyListener not reading keys?

I am using a JPanel with Graphics to make a game. I have implemented a KeyListener and I have added it to my JPanel. I cannot get it to read the keycodes, however. I added a print statement that I assumed would print anytime a key was pushed, but none of the keys I press are returning codes. Here is my JPanel constructor:

public Game()
{
    super();
    JPanel mazepanel = new JPanel();
    this.add(mazepanel);
    this.setVisible(true);
    this.addMouseListener(this);
    this.addKeyListener(this);
}

And here is my KeyListener.

public void keyTyped(KeyEvent kb)
{
    System.out.println("Key pressed: " + kb.getKeyCode());
    if (kb.getKeyCode() == KeyEvent.VK_UP)
    {
        forward = true;
    }
    else if (kb.getKeyCode() == KeyEvent.VK_LEFT)
    {
        left = true;
    }
    else if (kb.getKeyCode() == KeyEvent.VK_RIGHT)
    {
        right = true;
    }
    else if (kb.getKeyCode() == KeyEvent.VK_DOWN)
    {
        back = true;
    }
    else
    {

    }

    this.repaint();
}

Upvotes: 0

Views: 203

Answers (2)

Jase Pellerin
Jase Pellerin

Reputation: 397

Here is a good example of a KeyListener to work off of:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class KeyboardExample extends JPanel {

    public KeyboardExample() {
        KeyListener listener = new MyKeyListener();
        addKeyListener(listener);
        setFocusable(true);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Mini Tennis");
        KeyboardExample keyboardExample = new KeyboardExample();
        frame.add(keyboardExample);
        frame.setSize(200, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public class MyKeyListener implements KeyListener {
        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("keyPressed="+KeyEvent.getKeyText(e.getKeyCode()));
        }

        @Override
        public void keyReleased(KeyEvent e) {
            System.out.println("keyReleased="+KeyEvent.getKeyText(e.getKeyCode()));
        }
    }
}

From http://www.edu4java.com/en/game/game4.html

Upvotes: 0

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

Your JPanel is not focusable by default. Add

setFocusable(true);

to make it so.

Upvotes: 2

Related Questions