0

I want to addKeyListener to a JPanel but when I press two keys at the same time, just one of them executes. What is the solution to this problem - press two keys at the same time?

I have a class that extends JPanel

this.addKeyListener(new KeyListener() {

public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_W) {
            upPlayer2();
    }  if (e.getKeyCode() == KeyEvent.VK_A ){

            leftPlayer2();
        }

}
    });

Thanks.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
shayan
  • 79
  • 1
  • 9
  • 1
    I know you have tried yourself but could you please show that to us :) so that we can understand that you have tried and have minimal understanding of the problem being solved – Sage Dec 07 '13 at 17:00
  • This answer might help you: http://stackoverflow.com/a/753078/1068167 – span Dec 07 '13 at 17:18
  • Keyevents are fired one at a time with/without masks (alt, ctrl, etc). Your code will not work, e is one event it cannot possibly be another event in the same call to keyTyped. – arynaq Dec 07 '13 at 17:21

1 Answers1

1

Don't use a KeyListener. Swing was designed to be used with Key Bindings.

See Motion Using the Keyboard for more information and solutions.

camickr
  • 321,443
  • 19
  • 166
  • 288