views:

42

answers:

4
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 and "Unknown keyCode:0x0" for the second one.

What am I doing wrong?

A: 

You also need this to ctach the event, I think:

/**
     * 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);
        }
    }

And by the way, you should work on your accept rate, otherwise it will be likley, that nobody will answer your questions.

yan.kun
How do I work on my accept rate?
w4j3d
@w4j3d: By accepting an answer (presumably the best answer) by clicking the check mark below at the top left corner of the answer (below the big number).
Shynthriir
Alright, thank you
w4j3d
He does not need to "catch the event". He is receiving events properly.
Grodriguez
A: 

From the Java Documentation for a KeyEvent:

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

You are using a keyTyped event, thus the value being returned is VK_UNDEFIED.

You can, however, just use the following to get the character that was typed:

JOptionPane.showMessageDialog(null, e.getKeyChar());
Shynthriir
Pretty sure you added the e.getKeyChar() to your answer (via edit) after my answer was submitted, poor form.
Syntax
A: 

Use e.getKeyChar()

Syntax
A: 

You may get three types of events: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED events. The first two are associated to the action of pressing and releasing keys on the keyboard (which may or may not result in a character being typed), while the third one is associated with character input:

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

Your code is listening to KEY_TYPED events, but then using e.getKeyCode() which is only valid for KEY_PRESSED and KEY_RELEASED events.

Grodriguez