0
我的KeyListener沒有註冊任何鍵被按下,我能做些什麼來解決這個問題?我曾嘗試使用鍵碼而不是VK_DOWN格式,但這沒有什麼不同。我沒有使用一個JPanel ..爲什麼我的KeyListener不起作用?
import javax.swing.*;
import java.awt.event.*;
public class SnakeFrame extends JFrame
{
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 700;
private SnakeComponent scene;
class KeyPressListener implements KeyListener
{
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
switch(keyCode) {
case KeyEvent.VK_UP:
// handle up
System.out.println("Hello");
case KeyEvent.VK_DOWN:
// handle down
scene.a("d");
case KeyEvent.VK_LEFT:
// handle left
scene.a("l");
case KeyEvent.VK_RIGHT :
// handle right
scene.a("r");
}
KeyListener key = new KeyPressListener();
scene.addKeyListener(key);
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e) {}
}
class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
scene.moveSnake();
scene.eaten();
scene.gameOver();
}
}
public SnakeFrame()
{
scene = new SnakeComponent();
add(scene);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
KeyListener key = new KeyPressListener();
scene.addKeyListener(key);
ActionListener listener = new TimerListener();
final int DELAY = 80;
Timer t = new Timer(DELAY, listener);
t.start();
}
}
我試圖if/else語句代替開關外殼和不工作