klenium klenium - 8 months ago 37
Java Question

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 {
public void windowKeyPressed(KeyEvent event) {

In the
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.


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.:

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