Search code examples
javaeventsjavafxkeypress

Key press event isn't fired


In a javaFY project, I want to add a key pressed listener to the whole window. The root node in the window's FXML file is:

<VBox onKeyPressed="#windowKeyPressed" fx:controller="hu.kleni.tetris.EventController" ...>

And hte event handler class:

public class EventController {
    @FXML
    public void windowKeyPressed(KeyEvent event) {
        System.out.println(event.getCode());
    }
    ...
}

In the main() method, It just loads and launches the window. If I start the program, the windows shows up, but after I press a key, I can't see anything in the console. Did I miss something?

Edit: Although I could use this (and it works fine):

scene.setOnKeyPressed((event) -> {
    // maybe call EventController.windowKeyPressed(event);
})

, I'd prefer to define all event handlers in only the FXML file.


Solution

  • You'll need the root (VBox) to have focus for onKeyPressed to work.

    In your Application class, requestFocus() on your root after the Stage is shown, e.g.:

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));        
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
        root.requestFocus(); // add this, root is the VBox in your case
    }