Reputation: 53
I am taking help from Java:The complete reference(8th Ed) by Herbert Schildt to learn about Java. While reading, I found that KEY_TYPED event occurs only when a character is generated. Doesn't that mean that a character (0-9,A-Z) is generated? If so, then shouldn't the corresponding ASCII equivalents be passed as code to the KeyEvent constructor:
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
But the book says, for KEY_TYPED events, code will contain VK_UNDEFINED. Isn't code here defined with the key typed?
Upvotes: 2
Views: 156
Reputation: 6145
This is because a KEY_TYPED
event doesn't necessarily have a corresponding VK code. VK codes comes from the keyboard, and represent a key. If I press the 'a' key, I will see a key press event with VK_A code. Now, KEY_TYPED events, as you said, occur when a character is generated. The thing is, character are generated by the OS after translating VK codes through a character map that depends on the locale.
As an example, with my keyboard I can type an 'ö' with a certain combination of keys. This will fire a bunch of key events with VK_SHIFT, VK_DEAD_CIRCUMFLEX and VK_O, but only one KEY_TYPED event, with the 'ö' character. Worse, I can type a '†' by pressing 6 keys (ALT+0+1+4+1+4), yet again, only one KEY_TYPED event will be fired. Now, what VK code would you put in the event ? That doesn't really mean anything, so they decided to always put VK_UNDEFINED to stay consistent, even with simple characters.
Upvotes: 4