What should be done in the case of a java keylistener not working?

727    Asked by MadeleineHill in Java , Asked on Oct 10, 2022

 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 key=new HashSet();
    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.


Answered by Mahaboob Alam

Just figured out my problem regarding the java keylistener not working. 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



Your Answer

Interviews

Parent Categories