我正在尝试使用JFrame和keylistener在Eclipse中创建一个2D游戏。我的代码如下所示:
Main.java
public static void main(String[] args) {
DrawerManager game = new DrawerManager();
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(game);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addKeyListener(game);
}
DrawerManager.java
public class DrawerManager extends JPanel implements KeyListener {
public Scene scene = new GameScene( sceneContext );
int frame = 0;
public long last = 0;
public int ups = 30; //UPDATES PER SECOND
public DrawerManager() {
}
@Override
public void processKeyEvent(KeyEvent event) {
super.processKeyEvent(event);
}
@Override
protected void paintComponent(Graphics g) {
...
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
scene.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
scene.keyReleased(e);
}
}
GameScene.java
public class GameScene extends Scene{
GameContext context;
Player player;
public GameScene(SceneContext sceneContext) {
...
}
public void keyPressed(KeyEvent event) {
Logic here
}
public void keyReleased(KeyEvent event) {
Logic here
}
}
刚刚启动游戏时效果很好,但过了一段时间后它随机停止接收任何事件。我最初的想法是它与按住多个键有关,但似乎并非如此。根据我的测试,我可以看到由于某种原因压缩空间几秒钟使其再次起作用。请记住,问题非常随机,有时会立即发生,有时很长时间都不会发生。
问题似乎很奇怪,因为现在游戏非常简单,我看不到会干扰事件监听器的任何事情。我也尝试将代码导出到一个没有运气的jar文件中......
我在Mac上运行Eclipse Oxygen(4.7.1a)中的代码。
感谢任何帮助!