1
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请帮助:)

4

2 回答 2

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

}

附加阅读:如何编写关键监听器

于 2013-10-09T16:46:49.720 回答
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: ");
}
于 2013-10-09T16:52:10.350 回答