简体   繁体   中英

Java KeyListeners/KeyBinding - Clear Buffer - Java Game Development

I'm working on a Java Game and I've come to a point where I'm having problems with the KeyListeners/KeyBinding. What I basically want to do is temporarily disable the keyboard/do not allow more inputs when an animation occurs. This animation is generated by updating data.

What I currently get is that I press the key for the animation, the animation starts, and I press another key that does some other function. It gets added to the stack/queue(?) of the keyboardlistener and triggers when the first animation finishes.

I'm using a JPanel that implements KeyListener.

To give an idea of the code:

    public void keyPressed(KeyEvent arg0) {
      //Prevents Repeated keys
      pressed.add(arg0);
      if (pressed.size() == 1) {
            int key = ((KeyEvent) pressed.toArray()[0]).getKeyCode();
            if (key == KeyEvent.VK_ENTER) {
                doSomeAnimation();
            } else if (key == KeyEvent.VK_SPACE) {
                doADifferentAnimation();
            } 
            Update();
     }
}

Things I've tried:

1) Set the focusable(false) on the JPanel before the calls to the animations. Then set the focusable(true) and grab the focus when they've been completed.

2) Used a boolean to track when an animation occurred.

3) Use Key Bindings.

No matter what method I used, I always ended up with the problem that I would still take in input from the keyboard when the animation was occurring. Then, once that animation was finished, it'd go to the next element in the stack/queue(?) and process that. Also, these animations would need to occur more than once (so using an array of booleans to verify if it's been executed already wouldn't be helpful).

So, if you have any idea or help (or places to point me to) that would be greatly appreciated.

Some Extra Information: Java 1.6, IDE Eclipse, MVC structure. (This in question is the Controller/Model)

Assuming your animation is driven by an instance of javax.swing.Timer , the queue in question is the EventQueue , which runs events in "the same order as they are enqueued" by the Timer . Because it is impractical to stop other devices on the host platform from evoking your listeners, you have to track the effect in your application. As a concrete example, this game has several overloads of the model's move() method to handle input from disparate sources: keyboard, mouse or animation timer. The timer may be toggled on or off to see its effect. This example , which supplants the EventQueue with a custom implementation, may also offer some insight.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM