Search code examples
javajavafxfocusfxmlkeypress

Java: keyPressed events not firing when game is opened through application class


I'm making a game in java, and I want to extract it into a runnable Jar. To make this possible I made this class:

public class AfterglowApp extends Application {
    public void start(Stage primaryStage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(AfterglowApp.class.getResource("afterglow.fxml"));
        Pane root = fxmlLoader.load();
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(AfterglowApp.class, args);
    }
}

In my FXML controller I have a keyListener that triggers on keyPressed for the anchor pane in the FXML file. This works fine when I run it as an FXML application through Eclipse, but when I run it with the application class, no keypresses register (it still registers mouse clicks as normal though).

I have a feeling that the anchor pane of the FXML file loses focus, and that that's what's causing it to not register key presses, but I don't know how to fix that (if that even is the problem).

I realize there's probably something dumb I'm missing, but any help would be much appreciated.


Solution

  • I was correct, it was something stupidly easy. All I had to do was to call

    .requestFocusInWindow();
    

    on my anchor pane after the app started. Sorry for wasting the time of everybody who read this. I'll leave the question up in the unlikely event that somebody else gets themselves in a similar situation.