Java KeyListener gives me "Unknown keyCode: 0x0"

class KeyDemoFrame extends JFrame implements KeyListener
{
    String line1;
    KeyDemoFrame()
    {

        setTitle("hello");
        setSize(200,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        addKeyListener(this);
    }

    public void keyTyped(KeyEvent e) {
        line1 = e.getKeyText(e.getKeyCode());
        JOptionPane.showMessageDialog(null, e.getKeyCode());
        JOptionPane.showMessageDialog(null, e.getKeyText(e.getKeyCode()));

    }

    public void keyPressed(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }
}

When I press any key, I get "0" for the first message dialog box and "Unknown key code: 0x0" for the second.

What am I doing wrong?

+3
source share
6 answers

From the Java documentation for KeyEvent :

getKeyCode
Returns: integer code for the actual key on the keyboard. (For KEY_TYPED events, the key code is VK_UNDEFINED.)

You are using the keyTyped event, so the return value is VK_UNDEFIED.

However, you can use the following to get the character that was typed:

JOptionPane.showMessageDialog(null, e.getKeyChar());
0
source

, . Java . .

+2

e.getKeyChar()

+1

KeyCode KeyPressed , KeyTyped, , , , ​​ .

+1

, , :

/**
     * Notification that an event has occured in the AWT event
     * system
     * 
     * @param e Details of the Event
     */
    public void eventDispatched(AWTEvent e) {
        if (e.getID() == KeyEvent.KEY_PRESSED) {
            keyPressed((KeyEvent) e);
        }
        if (e.getID() == KeyEvent.KEY_RELEASED) {
            keyReleased((KeyEvent) e);
        }
        if (e.getID() == KeyEvent.KEY_TYPED) {
            keyTyped((KeyEvent) e);
        }
    }
0

: KEY_PRESSED, KEY_RELEASED KEY_TYPED . ( ), :

  • KEY_PRESSED KEY_RELEASED:
    • e.getKeyCode() returns a valid key code
    • e.getKeyChar() returns CHAR_UNDEFINED
  • For events KEY_TYPED:
    • e.getKeyChar() returns a valid Unicode char
    • e.getKeyCode() returns VK_UNDEFINED

Your code listens for events KEY_TYPED, but then uses e.getKeyCode()that is valid only for KEY_PRESSEDand events KEY_RELEASED.

0
source

Source: https://habr.com/ru/post/1770554/


All Articles