简体   繁体   中英

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.

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");
    }
});

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