我的KeyListener没有注册任何按键被按下,我该怎么办才能解决这个问题?我尝试过使用密钥代码而不是VK_DOWN格式,但这并没有什么区别。我没有使用jpanel ..
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语句而不是switch case并且不起作用
答案 0 :(得分:0)
KeyListener
需要处理两件事情,它需要注册的组件为focsuable
并且在生成密钥之前具有当前的键盘焦点,这是{{{ 1}}š
与关于该主题的所有其他问题一样,建议的解决方案是使用已设计的Key Bindings API来解决此问题,并让您控制以确定应在哪个焦点级别生成事件