我对Java KeyAdapter的工作方式有些陌生,并且使用KeyAdapter的以下代码正在获得意想不到的结果。无论是否调用isKeyPressed(),都在按住另一个键的同时按下一个键,就会出现问题。

注意:我知道这是很多代码,对此我深表歉意。我尽力将其隔离,我认为它主要位于下面keyHandler方法中的注释周围(keyHandler()如何将当前按下的键放入keysHeld中)。希望详尽的评论对您有所帮助。

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;
}


控制台输出:(按住leftArrow [37],然后按rightArrow [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
...

最佳答案

几点:


您不会使用keysHeld实例来填充KeyEvent数组,而是使用从Integer keyCodes派生的autoBoxed int对象。
如果要退出index中的while循环,则需要增加keyPressed变量。
您不应该使用==来比较Objects循环中的两个while


您可以使用以下内容进行测试:

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

10-06 09:50