Pregunta

No estoy familiarizado con el funcionamiento del Java KeyAdapter , y obtengo resultados inesperados con el siguiente código usando KeyAdapter . El problema ocurre cuando se presiona una tecla mientras otra tecla ya está presionada, independientemente de si se llama a isKeyPressed () .

Nota: Sé que esto es mucho código, y me disculpo. Hice lo mejor que pude para aislarlo, y creo que reside principalmente en los comentarios en el método keyHandler a continuación (cómo keyHandler () coloca las teclas presionadas actualmente en < code> keysHeld ). Esperemos que los comentarios completos sean útiles.

keyHandler:

ArrayList keysHeld = new ArrayList<KeyEvent>();

private void keyHandler()
{
    KeyAdapter keyListnr = new KeyAdapter()
    {
        public void keyPressed(KeyEvent e)
        { 
            int keyCode = e.getKeyCode();

            int index = 0;
            boolean found = false;
            while(!found && index<keysHeld.size()) //While not already found, and end of ArrayList not reached
            {
                System.out.print("errorCheck: keysHeld: "+keysHeld+", "+(Object)keyCode+" "); //PRINT
                if(keysHeld.get(index) == (Object)keyCode)
                {
                    System.out.println("found"); //PRINT
                    found = true; //This key is already recognized as held
                }
                else
                {
                    System.out.println("not found"); //PRINT
                    //This key is not recognized as held
                }
            }
            if(!found) //If key must be added to keysHeld
            {
                keysHeld.add(keyCode); //Add to list of held keys
            }
        System.out.println(keysHeld.toString()); //PRINT ArrayList of all held keys
    } //end of keyPressed


        public void keyReleased(KeyEvent e) //similar in concept to keyPressed
        {
         int keyCode = e.getKeyCode();

         int index = 0;
         boolean found = false;
         while(!found && index < keysHeld.size())
         {
          if(keysHeld.get(index) == (Object)keyCode)
          {
           keysHeld.remove(index); //remove key from keysHeld
           found = true;
          }
          else
          {
           index++;
          }
         }
         System.out.println(keysHeld.toString()); //PRINT ArrayList of all held keys
        } //end of keyReleased
    };
    addKeyListener( keyListnr );
}

isKeyHeld:

public boolean isKeyHeld(int e)
{
 int keyCode = e;
 Object key = (Object)keyCode;

 if(!keysHeld.isEmpty())
 {
  int index = 0;
  while(index<keysHeld.size())
  {
   if(keysHeld.get(index) == key)
   {
    return true;
   }
   index++;
  }
 }
 return false;
}

Salida de la consola: (mantuvo la flecha izquierda [37] y luego presionó la flecha derecha [39])

[37]
errorCheck: keysHeld: [37], 39 not found
errorCheck: keysHeld: [37], 39 not found
errorCheck: keysHeld: [37], 39 not found
errorCheck: keysHeld: [37], 39 not found
...
¿Fue útil?

Solución

Un par de puntos:

  • No está completando su matriz keysHeld con instancias de KeyEvent , sino con objetos autoBoxed Integer derivados del int keyCodes.
  • Necesita incrementar su variable index si quiere salir del bucle while en keyPressed
  • No debe utilizar == para comparar los dos Objetos en su while loop

Puede probar con algo como lo siguiente:

    if(keysHeld.get(index++).equals(new Integer(keyCode))

Otros consejos

Al manejar varias teclas, es mejor usar el método keyReleased (KeyEvent) : hace que sea más fácil manejar múltiples combinaciones de teclas durante una liberación de teclas.

Lo que noté fue que cuando estaba dentro de keyPressed () , solo podía capturar un carácter clave. En una keyReleased , pude capturar varios caracteres (como CTRL - V ).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top