본문 바로가기
Development/Java

keyTyped(KeyEvent e) 메소드내에서의 KeyEvent.VK_BACK_SPACE 오류 관련.

by 버들도령 2019. 7. 9.
728x90

keyTyped(KeyEvent e) 메소드내에서의 KeyEvent.VK_BACK_SPACE 오류 관련.

 

 Key Event 발생시 아래와 같은 순서로 호출이 된다.

Key Pressed(..) ▶ Key Typed(...)  Key Released(..)

 

이때!!!

백스페이스키를 눌렀을 경우 각 메소드에서 인식하는 Key Code는 어떨까??

Key Pressed(..) : 8번.
Key Typed(...) : 0번.  <----- 헉!!!! KEY_LOCATION_UNKNOWN = 0 번으로 인식한다. ㅡ.ㅡa
Key Released(..) : 8번.

KEY_LOCATION_UNKNOWN = 0번.
VK_BACK_SPACE = 8번.

 public void keyTyped(KeyEvent e) {
        System.out.println("Key Typed. " + e.getKeyCode());
        if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
            e.consume();
            System.out.println("BACKSPACE pressed.");
            return;
        }
}

만약에 위와 같은 코드를 작성하고, Back Space키를 줄기차게 놀러도... "BACKSPACE pressed."를 절대 찍지 못한다.

백스페이스키를 누르면 다음의 메시지만 프린트하겠죠.

"Key Typed. 0"

 

이를 위한 해결방법은??

해당 키에 대한 스트링 값으로 비교하여 처리하는 방법입니다.

if( e.paramString().indexOf("Backspace") != -1 ) {  ...  }

 

There was a JDC discussion that was helpful in figuring this 
out. http://forum.java.sun.com/thread.jsp?thread=124330&forum=57&message=1343359

public void keyTyped(KeyEvent e) {
  if(e.paramString().indexOf("Backspace") != -1) {
    System.out.println("Handle BACKSPACE pressed");
    e.consume();
  }
}

728x90

댓글