我正在制作游戏,当我介绍用户输入时,我遇到了这个问题。我向JPanel添加了一个KeyListener,但它根本不起作用。该程序由JFrame(WindowManager)中的JPanel(GameWindow)组成。游戏在GameLoop对象中启动,该对象实现了Runnable。 Level包含地图的所有信息。我读到如果Component是可聚焦的,KeyListener可以工作,所以我检查了面板是否可以聚焦并且程序返回true。也许这是一个线程问题,但我不知道为什么。
public class GameWindow extends JPanel {
private Level level;
private GameLoop gameLoop;
private LevelLoader levelLoader = new LevelLoader();
private WindowManager windowParent; // A JFrame
public GameWindow(WindowManager windowParent){
super();
this.windowParent = windowParent;
setBackground(Color.BLACK);
gameLoop = new GameLoop(this);
level = levelLoader.loadLevel(1);
setFocusable(true);
requestFocusInWindow();
addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
System.out.println("typed");
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("pressed");
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("released");
}
});
start();
}
private void start(){
Thread thread = new Thread(gameLoop);
thread.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
level.paintLevel(g,getSize());
}
}
答案 0 :(得分:-1)
问题解决了我需要在将JPanel添加到JFrame并变得可见后请求焦点。