klenium klenium - 1 year ago 77
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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download