-1

I tried this but it did not work.

I have to run an animation when the key is pressed.

My code:

case KeyEvent.VK_RIGHT:

while(KeyEvent.KEY_PRESSED){

  estado = ANDA0;

  posX += 10;

}

estado = PARADO;

break;
Huy Nguyen
  • 2,025
  • 3
  • 25
  • 37
Giovanni
  • 13
  • 6

2 Answers2

2

Your while loop will completely overwhelm the GUI event thread, preventing any actions from occurring, including animation actions and key reading events. Instead, I suggest that you:

  • Use Key Bindings if this is Swing, not a KeyListener.
  • Change use a Swing Timer as an animation loop, not a thread freezing while (true) loop.
  • On key press (from the key bindings), change the state a state field
  • On key release (again from bindings), revert the state of that same field
  • Base what happens in your animation loop by the state of the state field changed above.

For example, please have a look at this answer and example code of mine

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
-1

Something like this using the KEY_RELEASED event should do the trick:

    case KeyEvent.VK_RIGHT:
    if (KeyEvent.getID() == KeyEvent.KEY_PRESSED)
        bool = true;

    while(bool){

        estado = ANDA0;
        posX += 10;
        if (KeyEvent.getID() == KeyEvent.KEY_RELEASED)
        bool = false;

    }

    estado = PARADO;

  break;
Vaibhav Bajaj
  • 1,934
  • 16
  • 29
  • 2
    Out of curiosity, how does this work? In the Java i know of, busy-waiting for an event in the event handling thread would make the program freeze up. – cHao Aug 10 '16 at 23:34
  • @cHao I was presuming since he has used a `switch-case` that the key has already been pressed. – Vaibhav Bajaj Aug 10 '16 at 23:35
  • Yeah, but it has to be released before you get a `KEY_RELEASED` event. Which means you're waiting for a new event. – cHao Aug 10 '16 at 23:36
  • So `KeyEvent.KEY_RELEASED` should evaluate to false till then, right? OH NVM, I get your point. I will edit my answer now – Vaibhav Bajaj Aug 10 '16 at 23:37
  • 1
    It'll evaluate to false _forever_, i'd think, because you don't return, which means you're tying up the event handling thread, which means that next event will never get processed. That's why i was asking -- something seems very weird about this. – cHao Aug 10 '16 at 23:38
  • 1
    You're still busy-waiting, though. And that event you already have is not going to change its type. – cHao Aug 11 '16 at 00:04