KeyTypedEvent KeyEvent KeyCode is always 0?

I have a Java Swing application in NetBeans IDE.

I made a form and bound the KeyListener to my various controls as such:

jButton1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { keyTypedEvent(evt); } }); 

and keyTypedEvent is defined as such:

 private void keyTypedEvent(java.awt.event.KeyEvent evt) { System.out.println(evt); appendDisplay(String.valueOf(evt.getKeyChar())); } 

I added println to evt to find out what is happening and check if my keylistener is working. When I create and run my application, I realized that the output is always keycode = 0

To test this, I changed my println to evt.getKeyCode() and it always returns 0.

I could have completely misinterpreted what KeyCode does, but I thought it would follow the values ​​in the Oracle documentation here:

http://docs.oracle.com/javase/7/docs/api/constant-values.html#java.awt.event.KeyEvent.VK_ESCAPE

For example, VK_ESCAPE has a value of 27.

+8
java swing keylistener keyevent
source share
3 answers

The keyTyped() event is used only for keys that generate character input. If you want to know when any key is pressed or released, you need to implement keyPressed() or keyReleased() .

In KeyEvent API:

Key typed events are of a higher level and usually are platform or keyboard independent. They are generated when a Unicode character is entered, and this is the preferred way to learn about character input ....

For keystrokes and key releases, the getKeyCode method returns a keyCode event. For key typed events, the getKeyCode method always returns VK_UNDEFINED.

+22
source share
+3
source share

It depends on the keystroke. You probably need a KeyListener overriding the keyPressed method, because keyTyped does not start on non-printable characters.

Look at the difference between keyTyped and keyPressed here: KeyListener, keyPressed vs keyTyped

0
source share

All Articles