我很確定我錯過了這裏很簡單的東西,但我找不到它!KeyListener沒有添加
這裏是我的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);
我甚至在我keyPressed
方法添加一個System.out.println
,它不會打印!我錯過了什麼?
我看不到'requestFocusInWindow()'或同步訪問共享'keyPressed'。另見[*初始線程*](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)。 – trashgod
@trashgod好的,明天我會試試;我現在要睡覺 – Doorknob