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) {

}
4

1 回答 1

3

如果没有您的代码,我只能告诉您,通常当人们问这个问题时,他们不知道该接口KeyListener包含三个方法,正如 Agusti-N 在此处的回答中所说:

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

如果您使用keyTyped并且正在使用event.getKeyCode()来检查输入的字符,这将不起作用。你应该使用getKeyChar()forkeyTypedgetKeyCode()forkeyPressedkeyReleased。否则你会得到null. 只有在没有其他选择的情况下才应该使用它,在大多数情况下,您想使用Key Bindings

于 2013-03-28T19:45:52.657 回答