Crossoni
Crossoni

Reputation: 393

JavaFX keyboard input stops working after adding buttons

I am building a game engine as a school project. When I add button to the same group as where I have my canvas, I can't control my player anymore with keyboard. Buttons and everything else still works like normal.

My code is pretty huge, so this is a simplified code of the problem:

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();
        }
    }
}

There is probably something happening on the background which I just don't understand. I can show my Input class code too if somebody wants to see it, but in my understanding it's not necessary.

I have tried using AnchorPane as main root and make a separate groups for buttons and canvas which I add the to the AnchorPane, but that did not help at all. That was pretty much the only offered solution I could find from google.

Upvotes: 1

Views: 316

Answers (1)

Crossoni
Crossoni

Reputation: 393

Adding btn.setFocusTraversable(false); fixed the problem, thanks to Luxusproblem for providing the answer!

Upvotes: 1

Related Questions