0

I have a program which produces a JFrame and then a JPanel on top of it. For the program, I have tried implementing the KeyListener and then adding the methods (for both components), but the program does not pick any of my key strokes up. What am I doing wrong?

EDIT

This is my code. It is a part of the class which creates the JFrame. It still does not pick up the press of the ESC key.

@Override
public void keyTyped(KeyEvent e) {

}

@Override
public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();

    if(keyCode == KeyEvent.VK_ESCAPE){
        System.out.println("Hi");

    }else{
        System.out.println("Hello");

    }

}

@Override
public void keyReleased(KeyEvent e) {

}
Chandrayya G K
  • 8,719
  • 5
  • 40
  • 68
user1546859
  • 240
  • 2
  • 10

1 Answers1

3

Without your code, all I can tell you is that usually when people ask this they don't know that the interface KeyListener contain three methods as Agusti-N states in their answer here:

void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)

If you use keyTyped and you are using event.getKeyCode() to check for the character entered, this will not work. You should use getKeyChar() for keyTyped and getKeyCode() for keyPressed and keyReleased. Otherwise you'll get null. You should only use this if you do not have any other alternative, in most cases you want to use Key Bindings.

Community
  • 1
  • 1
0x6C38
  • 6,796
  • 4
  • 35
  • 47
  • 1
    Ah, never knew about this difference between `code` and `character` in this context. – asgs Mar 28 '13 at 20:01
  • Also, you may well have forgotten to register the KeyListener with the JPanel. Use panel.addKeyListener( listener ). – Nathan Mar 28 '13 at 20:02
  • @Mr D did you refer to the part of the [`KeyEvent` Javadoc](http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html#getKeyChar()) which says "For KEY_TYPED events, the keyCode is VK_UNDEFINED." – asgs Mar 28 '13 at 20:05
  • Yes, actually I found out not long ago when i was working on some javafx project and I read the NetBeans tip for it – 0x6C38 Mar 28 '13 at 20:10