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,请帮助:)
最佳答案
您可能需要请求重点。
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