我正在将游戏引擎构建为学校项目。当我将按钮添加到与画布所在的组相同的组时,我再也无法通过键盘控制播放器。按钮和其他所有功能仍然正常运行。
我的代码非常庞大,因此这是问题的简化代码:
public abstract class GEngine extends Application {
public void start(Stage theStage) throws Exception {
try {
this.stage = theStage;
Group root = new Group();
Scene theScene = new Scene(root);
stage.setScene(theScene);
Canvas canvas = new Canvas(windowWidth, windowHeight);
root.getChildren().add(canvas);
Button btn = new Button("new");
btn.setOnMousePressed(e->System.out.println("press"));
root.getChildren().add(btn);
Timeline gameLoop = new Timeline();
gameLoop.setCycleCount(Timeline.INDEFINITE);
// Handle input
theScene.setOnKeyPressed(Input::handlePressed);
theScene.setOnKeyReleased(Input::handleReleased);
// Control game loop and it's speed
KeyFrame kf = new KeyFrame(
Duration.seconds(0.017), // 60 FPS
(e)->this.controlGameLoop());
gameLoop.getKeyFrames().add( kf );
gameLoop.play();
stage.show();
} catch (Exception e) {
e.printStackTrace();
stop();
}
}
}
背景可能发生了一些我不了解的事情。如果有人希望看到我的Input类代码,我也可以显示它,但是据我了解,这不是必需的。
我尝试使用AnchorPane作为主根,并为按钮和画布创建一个单独的组,将它们添加到AnchorPane中,但这根本没有帮助。那几乎是我可以从Google找到的唯一提供的解决方案。
添加btn.setFocusTraversable(false);
固定的问题,这要归功于Luxusproblem提供答案!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句