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);
}
所以这是我的框架,我在这里做错了什么吗?因为当我按任意键时不会调用键事件,请帮忙:)
最佳答案
您可能需要请求焦点。
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);
}
关于java - 按键事件未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19277866/