1
\$\begingroup\$

I have been having a problem with the JOGL KeyListener where if I hold down a key, it would register the key as pressed for around 1 second, then it would start quickly switching back and forth between pressed and unpressed. However, if I hold more than one key at once, sometimes the key listener "forgets" about one of the keys and keeps it held down (like it should) while releasing the other one (when it shouldn't).

Here is the relevant code in the class:

import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;

import java.util.HashSet;
import java.util.Set;

public class KeyInput implements KeyListener {
    private static Set<Short> key=new HashSet<Short>();
    public void keyPressed(KeyEvent keyEvent) {
        key.add(keyEvent.getKeyCode());
        System.out.println("added " +keyEvent.getKeyChar());
    }

    public void keyReleased(KeyEvent keyEvent) {
        key.remove(keyEvent.getKeyCode());
        System.out.println("removed " +keyEvent.getKeyChar());
    }

    public static boolean getKey(short k){
        return key.contains(k);
    }
}

I tried using other methods of storing the keys to no avail. How should I fix it so that it properly registers and remembers held down keys? I tried a different program with Swing and it worked fine. It has the exact same code as shown here.

\$\endgroup\$
2
  • \$\begingroup\$ Can you rule out hardware or OS issues? For example, you can use that many keys normally in other programs. Is there a way that you can consistently reproduce it with, say, two keys? \$\endgroup\$
    – Jay
    Mar 18, 2019 at 2:45
  • \$\begingroup\$ @Jay I have a different program using the Swing framework and it works fine on the same PC. \$\endgroup\$
    – ImTheSquid
    Mar 18, 2019 at 12:15

1 Answer 1

1
\$\begingroup\$

Just figured out my problem. It turns out that OpenGL had auto-repeat enabled (which is the default on Windows), which was giving me the rapid on-off values. If anyone else has this problem, the solution is to add this code snippet before removing a key from an index:

if(keyEvent.isAutoRepeat()){
     return;
}

This would go in the keyReleased method.

\$\endgroup\$
1
  • \$\begingroup\$ where we need to add this code \$\endgroup\$
    – DRV
    Mar 27 at 4:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .