keypressed事件未被调用

时间:2013-10-09 16:41:44

标签: java swing awt

public GuiC() {
    getContentPane().addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("hi");

        }
    });
    setBackground(Color.GREEN);
    setTitle("Hi!");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 500, 500);
    getContentPane().setLayout(null);

}

所以这是我的框架我在这里做错了什么?因为当我按任意键时keyevent没有被调用请帮助:)

2 个答案:

答案 0 :(得分:0)

您可能需要请求焦点。

public GuiC() {
    this.getContentPane().requestFocus(); //request focus here
    this.getContentPane().addKeyListener(new KeyListener() {
    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("hi: " + e.getKeyChar());

    }
});
    setBackground(Color.GREEN);
    setTitle("Hi!");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 500, 500);
    getContentPane().setLayout(null);

}

补充阅读:How to Write a Key Listener

答案 1 :(得分:0)

你的代码很好。 我通常使用KeyListener

getContentPane().addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("hi");

请参阅此处获取教程:

http://java.about.com/od/Handling-Events/ss/A-Keylistener-Example-Program.htm
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

我个人不喜欢匿名课程解决方案。

Oracle的做法更加清晰。

//make your class implement KeyListener
public class KeyEventDemo ...  implements KeyListener ... {  

//use `this` as the listener
typingArea.addKeyListener(this);  <<-- simple

//Add the relevant listeners to the class
/** Handle the key-pressed event from the text field. */
public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
}

/** Handle the key-released event from the text field. */
public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
}