Jack Dane
Jack Dane

Reputation: 402

Java KeyListener discarding lower case letters

I am trying to detect when a specific key is pressed inside a text field.

if((event.getKeyCode()>=KeyEvent.VK_A && event.getKeyCode()<=KeyEvent.VK_Z)){//65 to 90
    System.out.println("pass");
    event.consume();
}

For some reason this will only detect and stop uppercase letters such as "A" but won't stop "a". How would i make this program stop lowercase letters.

Upvotes: 2

Views: 1620

Answers (1)

Adam
Adam

Reputation: 36703

getKeyCode() happens to return the ASCII code, and you're only filtering out A to Z codes, i.e. 65 to 90.

getKeyChar() returns a char if you're using KEY_TYPED events. This can be used to detect both 'A' to 'Z' and 'a' to 'z'. i.e.

if (Character.isAlphabetic(event.getKeyChar())) {
     // ....
}

Upvotes: 3

Related Questions