我很确定我在这里遗漏了一些非常简单的东西,但我就是找不到!
这是我GamePanel
班级的声明:
private class GamePanel extends JPanel implements KeyListener {
在它的构造函数中是:
addKeyListener(this);
同样在构造函数中:
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
index ++;
index = index >= 15 ? 0 : index;
if (aPress) {
playerX --;
}
if (dPress) {
playerX ++;
}
repaint();
try {
Thread.sleep(25);
} catch (InterruptedException e) {}
}
}
}).start();
在课堂里:
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed!");
if (e.getKeyCode() == KeyEvent.VK_A) {
aPress = true;
}
if (e.getKeyCode() == KeyEvent.VK_D) {
dPress = true;
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_A) {
aPress = false;
}
if (e.getKeyCode() == KeyEvent.VK_D) {
dPress = false;
}
}
最后:
JFrame f = new JFrame();
//set up f
f.add(new GamePanel());
f.setVisible(true);
我什System.out.println
至在我的keyPressed
方法中添加了一个,它不会打印!我错过了什么?