PurkkaKoodari
PurkkaKoodari

Reputation: 6809

Disabling key repeat in Swing

I'm developing a Java/Swing application, and I'm making my own handling for key events using a KeyListener on my JFrame.

My problem is, the key repeat feature of the OS is causing multiple keyPressed events to occur when I hold down a key, when I would like to only receive one.

One solution would be to keep the states of the keys in an array, and only accept the event if the state changes.

private boolean keysDown[] = new boolean[0x10000];
public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if (0 <= key && key <= 0xFFFF) {
        if (keysDown[key]) return;
        keysDown[key] = true;
    }
    // ...
}
public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if (0 <= key && key <= 0xFFFF) {
        if (!keysDown[key]) return;
        keysDown[key] = false;
    }
    // ...
}

This works, but is very clumsy, and while I only seem to find keycodes in the range 0 to 216-1, I'm not sure if ones outside that range can exist. (getKeyCode() returns int.) Another problem is that pressing down a key, releasing it while in another window, and pressing it again in my application would not register the event.

So, is there a better way to either

Upvotes: 4

Views: 1627

Answers (1)

VGR
VGR

Reputation: 44414

Replace your boolean array with HashSet<Integer> or TreeSet<Integer>. The key repeat is a function of the OS, so there is no way to disable it, only account for it.

Upvotes: 3

Related Questions