문제

나는 Java가 어떻게 작동하는지 다소 익숙하지 않습니다. KeyAdapter 작동하고 다음 코드를 사용하면 예상치 못한 결과가 나타납니다. KeyAdapter.해당 문제는 다른 키를 이미 누르고 있는 동안 키를 눌렀을 때 발생합니다. isKeyPressed() 호출됩니다.

메모:나는 이것이 많은 코드라는 것을 알고 사과드립니다.나는 그것을 분리하기 위해 최선을 다했고 그것은 주로 다음의 댓글 주위에 있다고 생각합니다. keyHandler 아래 방법(어떻게 keyHandler() 현재 누르고 있는 키를 keysHeld).세심한 댓글이 도움이 되었으면 좋겠습니다.

키 핸들러:

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

콘솔 출력:(왼쪽 화살표[37]를 누른 다음 오른쪽 화살표[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 에서 파생 된 개체 int 키 코드.
  • 당신은 당신의 증분이 필요합니다 index 당신이에서 벗어나려면 변수입니다 while 루프를 넣습니다 keyPressed
  • 사용해서는 안됩니다 == 둘을 비교합니다 Objects 당신의 while 고리

다음과 같은 방법으로 테스트 할 수 있습니다.

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

다른 팁

여러 키를 처리할 때는 다음을 사용하는 것이 가장 좋습니다. keyReleased(KeyEvent) 방법:키를 놓는 동안 여러 키 조합을 더 쉽게 처리할 수 있습니다.

제가 주목한 것은 내부에 있을 때였습니다. keyPressed(), 핵심 캐릭터 하나만 캡처할 수 있습니다.에 keyReleased, 여러 문자를 캡처할 수 있었습니다(예: CTRL 키-V).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top