0

I have 2 objects in my JFrame windows, I want them to follow my keys(arrows or buttons ASDW) as arrows control one object and ASDW control the other one, my problem is the objects are not flawless, they move in the direction I press but if I press 'D' (it starts moving right) and then I press 'W' it will not start moving up, it can control only one key press at a time.

Here is my code:

addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_DOWN)
            vely2 = 1;
        else if (e.getKeyCode() == KeyEvent.VK_UP)
            vely2 = -1;
        else if (e.getKeyCode() == KeyEvent.VK_LEFT)
            velx2 = -1;
        else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
            velx2 = 1;
        else if (e.getKeyCode() == KeyEvent.VK_S)
            vely1 = 1;
        else if (e.getKeyCode() == KeyEvent.VK_W)
            vely1 = -1;
        else if (e.getKeyCode() == KeyEvent.VK_A)
            velx1 = -1;
        else if (e.getKeyCode() == KeyEvent.VK_D)
            velx1 = 1;
        b1.setLocation(b1.getLocation().x + 5 * velx1, b1.getLocation().y + 5 * vely1);
        b2.setLocation(b2.getLocation().x + 5 * velx2, b2.getLocation().y + 5 * vely2);
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        vely2 = 0;
        vely1 = 0;
        velx1 = 0;
        velx2 = 0;
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
    }
});

How can I make it move like in this example. Thanks :)

DAVIDBALAS1
  • 484
  • 10
  • 31
  • So, you basically want to be able to check if 2 or more keys are pressed? If so, [check this](http://stackoverflow.com/questions/2623995/swings-keylistener-and-multiple-keys-pressed-at-the-same-time) – Frakcool Mar 30 '16 at 16:53
  • See [http://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key](http://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key) – FredK Mar 30 '16 at 16:54
  • Use Key Bindings. [For example](http://stackoverflow.com/questions/13528953/detecting-multiple-keypresses-in-java). Also have a look at the [many similar questions that can be found on this subject](https://www.google.com/webhp?sourceid=chrome-instant&rlz=1C1CHKZ_enUS436US436&ion=1&espv=2&ie=UTF-8#q=java+swing+more+than+one+key+pressed+site:http:%2F%2Fstackoverflow.com%2F). – Hovercraft Full Of Eels Mar 30 '16 at 17:02
  • i would have answered it but someone closed it... – hoyah_hayoh Mar 30 '16 at 17:03
  • @hoyah_hayoh thx anyway :P – DAVIDBALAS1 Mar 30 '16 at 17:10
  • Check out the `Motion With Multiple Keys Pressed` section from [Motion Using the Keyboard](https://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/) which contains a working example. The link explains why you should be using `Key Bindings` instead of a KeyListener. – camickr Mar 30 '16 at 18:28

0 Answers0