Issue with Keypressed event in JavaFx in Java 8

java, java-8, javafx

Solution

The GridPane doesn't have the focus. Try to invoke `requestFocus` when the stage is shown.

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class SampleApp extends Application {
    public static void main(String[] args) {
        launch(SampleApp.class);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Scene scene = new Scene(FXMLLoader.load(getClass().getResource("/sample/Sample.fxml")));
        primaryStage.setScene(scene );
        primaryStage.show();
        scene.getRoot().requestFocus();
    }
}

Problem

I recently updated my java 7 to java 8. I have an application that takes in the keypressed event and check whether the keypressed is a navigational key and act accordingly. Below is a mcve My controller code: ``` package sample; import javafx.fxml.FXML; import javafx.scene.input.KeyEvent; public class Controller { @FXML private void keyPressed(KeyEvent evt) { System.out.println("Key Pressed"); } } ``` My FXML file: ``` <?xml version="1.0" encoding="UTF-8"?> //I removed all the imports in this post... My original fxml has all the imports... <GridPane id="gridPaneId" alignment="CENTER" focusTraversable="true" gridLinesVisible="true" hgap="10.0" onKeyPressed="#keyPressed" prefHeight="400.0" prefWidth="300.0" vgap="10.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="sample.Controller" /> ``` The issue is that my code completely works fine if I run it using Java 7. When I try to run it using java 8, my UI shows up without any issues but the program is not recognizing the keypressed event. What could be the reason.

Original source