我有一个类 World 如下:
public class World extends JFrame implements KeyListener {
public boolean left = false, right = false, back = false, fwd = false;
public World() {
this.setSize(600, 600);
this.setVisible(true);
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getExtendedKeyCode() == KeyEvent.VK_LEFT) left = true;
if(e.getExtendedKeyCode() == KeyEvent.VK_RIGHT) right = true;
if(e.getExtendedKeyCode() == KeyEvent.VK_UP) fwd= true;
if(e.getExtendedKeyCode() == KeyEvent.VK_DOWN) back = true;
System.out.println("L:"+left+" R:"+right+" F:"+fwd+" B:"+back);
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getExtendedKeyCode() == KeyEvent.VK_LEFT) left = false;
if(e.getExtendedKeyCode() == KeyEvent.VK_RIGHT) right = false;
if(e.getExtendedKeyCode() == KeyEvent.VK_UP) fwd= false;
if(e.getExtendedKeyCode() == KeyEvent.VK_DOWN) back = false;
System.out.println("L:"+left+" R:"+right+" F:"+fwd+" B:"+back);
}
@Override
public void keyTyped(KeyEvent e) {}
}
理论上,这应该在按键或按键释放时触发,但是,它不会。框架中的组件绘制正确。
框架被实例化如下:
World m = new World();
m.getContentPane().setBackground(Color.BLACK);
我似乎无法让关键听众开火。没有系统输出。有什么想法吗?