Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keylistener not working for JPanel

I am trying to do something when one of the arrow keys are pressed using the KeyListener in my JPanel class. Here is my code:

public class TestPanel extends JPanel implements KeyListener{

    public TestPanel(){
        this.addKeyListener(this);
        this.setFocusable(true);
        this.requestFocusInWindow();
    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right");

        }

        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left");
        }

    }

    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
}

My main method adds a new instance of this panel to a frame and displays it. Do I need to add the keylistener to the JFrame? In my case, this would be difficult and inefficient, so I would like to make it work with this JPanel if possible. Anyone know what I am doing wrong?

EDIT: Key Bindings code that does not work either:

public class GamePanel extends JPanel implements ActionListener{

//Constructor
public GamePanel(){

    setupKeyBinding();
    this.setFocusable(true);
    this.requestFocusInWindow();


}

private void setupKeyBinding() {
    int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
    InputMap inMap = getInputMap(condition);
    ActionMap actMap = getActionMap();

    inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
    actMap.put("Left", new leftAction());
}

private class leftAction extends AbstractAction {

       public void actionPerformed(ActionEvent e) {
          System.out.println("test");
       }
}

public void actionPerformed(ActionEvent e) {
    //some other game info
}
} 

Can someone tell me why this doesnt work either? (my second action listener is for other stuff needed for my game)

like image 943
user2373733 Avatar asked May 13 '13 20:05

user2373733


1 Answers

For receives key events on JPanel you must set focus:

setFocusable(true);
requestFocus(); 

the JPanel now has focus, so it receives key events

like image 101
Dmitriy Potapov Avatar answered Nov 12 '22 17:11

Dmitriy Potapov