KeyTypedEvent KeyEvent's KeyCode is always 0?
Asked Answered
R

3

19

I have a Java Swing application in the NetBeans IDE.

I made a form and attached a 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 a println to the evt to see what happens and to verify that my keylistener does work. When I build and run my application, I realized that the output always seems to have a keycode = 0

To verify this, I had changed my println to be evt.getKeyCode() and it is always returning 0.

I could be completely misinterpreting what KeyCode does, but I thought that it would coorespond with the values in Oracle's documentation here:

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

For instance, VK_ESCAPE has a value of 27.

Rigel answered 5/2, 2013 at 19:1 Comment(1)
Don't use KeyListener. Either use DocumentListener or Swing Key bindings.Heterocercal
M
33

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

From the KeyEvent API:

"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered, and are the preferred way to find out about character input....

For key pressed and key released events, the getKeyCode method returns the event's keyCode. For key typed events, the getKeyCode method always returns VK_UNDEFINED.

Mcreynolds answered 5/2, 2013 at 19:7 Comment(0)
P
3
Pound answered 5/2, 2013 at 19:15 Comment(0)
V
0

It very depends on key that has been pressed. Probably you need KeyListener with keyPressed method override, because keyTyped not triggered on non-printable characters.

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

Verenaverene answered 5/2, 2013 at 19:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.