Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

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

Asked by Madeleine Hill Oct 10, 2022 1.5K views 1 answer
Share

About this question

 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.

Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.