alh
alh

Reputation: 2599

How to lock KeyListener while key is pressed

I added the following KeyListener to my button and noticed that if I hold any key down, it starts firing continuously as though I were pressing and releasing it very fast. I never release the key, yet the "a: released" message is still being printed in my console. Why is the release listener being fired and how can I stop the repeated key presses? I just want a single "a: pressed" for as long as I hold the key and then a single "a: released" when I release the key.

button.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println(e.getKeyChar() + ": pressed");
    }

    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println(e.getKeyChar() + ": released");
    }
});

Is there anyway to make the methods act like synchronized methods even though (I'm assuming) new threads aren't being created for the repeated events.

Upvotes: 0

Views: 1333

Answers (1)

tcb
tcb

Reputation: 2824

You can use an additional field to indicate that the button was pressed:

button.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {
    }

    private boolean pressed = false;

    @Override
    public void keyPressed(KeyEvent e) {
        if (!pressed) {
            System.out.println(e.getKeyChar() + ": pressed");
            pressed = true;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        pressed = false;
        System.out.println(e.getKeyChar() + ": released");
    }
});

Upvotes: 1

Related Questions