0

I am trying to write a piece of code so that when a key is pressed it will execute something, but then the key will have to be released and then repressed again in order to retrigger the event. So if the user just holds down the key, it wont keep doing it over and over, instead they will have to press and release repeatedly.
So far, I have:

if(keyLifted)
{
    if(Keyboard.isKeyDown(45))
    {
        keyLifted = false;
        dostuff;
    }
    else if(Keyboard.isKeyDown(46))
    {
        keyLifted = false;
        dostuff();
    }
    else
    {
        keyLifted = true;
    }
}

but this is flawed for obvious reasons (it will only reset the key to being unlifted if the key is already lifted: if the key was pressed, it wont be set to unpressed). I have tried a couple variations, but I just cant get it to work.

Thanks in advance for any help!

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Htuy
  • 9
  • 3
  • 4
    Why don't you take keypress and keyrelease events to handle keyboard status changes? – keltar May 15 '12 at 06:30
  • @user1296964 Please do *not* add tags for languages other than the one you are using. Tag spam is no less rude than email spam :) – Andrew Barber May 15 '12 at 06:32
  • Thanks Keltar. Seems like a silly oversite, but I'm so tired I probably would have just looked at the code for an hour and then given up instead of seeing that :) – Htuy May 15 '12 at 06:36

1 Answers1

0

You should use a KeyListener to capture keyboard events. Here you go:

public class KeyListenerExample extends JFrame {
    public KeyListenerExample() {
        addKeyListener(new KeyAdapter() {
            private boolean keyLifted;

            public void keyReleased(KeyEvent e) {
                keyLifted = true;
            }

            public void keyPressed(KeyEvent e) {
                keyLifted = false;
                switch (e.getKeyChar()) {
                    case 45:
                        doStuff();
                        break;

                    case 46:
                        doStuff();
                        break;
                }
            }
        });
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void doStuff() {
        System.out.println("stuff");
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new KeyListenerExample();
    }
}

I just kept the keyLifted because it is in your example. But I think for the usual keyboard stuff you don't need it.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45