0

I am trying to check if the user typed the y key, but I want it to be lowercase. I don't know how to check that. I am using if (e.getKeyCode()==KeyEvent.VK_Y), but I need the y key to be lowercase, when it is capital it is messing up my code.

Arcaniaco
  • 400
  • 2
  • 10
Sara
  • 3
  • 1

4 Answers4

2

getKeyCode returns the code of the key pressed, regardless of the intent or modifiers. To see if the shift modifier is applied, try using getModifiers() on the event.

Note that these key events are low-level, so making sense of the events in a more natural way is going to be more complex.

ash
  • 4,867
  • 1
  • 23
  • 33
  • This will not work with `Caps Lock` is on – Oleg Cherednik Jun 24 '21 at 21:29
  • Caps Lock doesn't show up in the modifiers? If not, then this feels like it is too low-level for things like capitals - unless the developer really wants to keep track of every modifier key's state (yuck). – ash Jun 24 '21 at 21:40
1

Maybe try something like

KeyEvent.getKeyText(e.getKeyCode()).equalsIgnoreCase("y")

This converts the keycode to a string then compares it case insensitive.

Or if you only want to accept lowercase just equals e.g.

KeyEvent.getKeyText(e.getKeyCode()).equals("y")
James Mudd
  • 1,816
  • 1
  • 20
  • 25
0

The method getKeyCode() happens to return the ASCII code, and the value of constant VK_Y is a integer 89 (reference). This value corresponds to char Y from ASCII table.

If you want a lowercase, use the corresponded value to y instead of constant KeyEvent.VK_Y. According the ASCII table, a integer 121 corresponds to char y.

So, you can do like:

if (e.getKeyCode() == 121)

or:

if (e.getKeyCode() == 'y')
Arcaniaco
  • 400
  • 2
  • 10
0
if (e.getKeyCode() == 'y') {
    //...
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35