Search code examples
javajtextfieldkeylistenerkeyevent

The method getKeyCode() is undefined for the type KeyEvent


I am trying to add a keyListener to my JTextField. From what i see every one is using getKeyCode() method for the KeyEvent. I keep getting the error in Eclipse that

The method getKeyCode() is undefined for the type KeyEvent*

What did I do Wrong?...

Here is my code:

TF_Message.addKeyListener(new KeyAdapter() 
{
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER)
        {
            ACTION_B_SEND();
        }
    }
});

Solution

  • Don't use a KeyListener.

    A JTextField is designed to be used with an ActionListener:

    textField.addActionListener(...);
    

    The ActionListener will be invoked when the Enter key is pressed.

    ACTION_B_SEND();
    

    Also, methods should NOT start with an upper case character. Learn by example from the Java API and don't make up your own conventions.

    Same with variable names. They should NOT start with an upper case character.