Чтобы эффективно добавить обработчики ключевых событий на панель, сначала нужно запросить фокус на панели.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class PanesKeyEventsApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
StackPane stackPane1 = new StackPane();
stackPane1.setPrefSize(200, 200);
stackPane1.setStyle("-fx-background-color: purple;");
StackPane stackPane2 = new StackPane();
stackPane2.setPrefSize(200, 200);
stackPane2.setStyle("-fx-background-color: yellow;");
HBox hBox = new HBox(stackPane1, stackPane2);
Scene scene = new Scene(hBox);
stage.setScene(scene);
stage.show();
stackPane1.setOnMouseClicked(event -> stackPane1.requestFocus());
stackPane2.setOnMouseClicked(event -> stackPane2.requestFocus());
stackPane1.addEventHandler(KeyEvent.KEY_PRESSED, event -> System.out.println("purple key pressed " + event.getCode()));
stackPane2.addEventHandler(KeyEvent.KEY_PRESSED, event -> System.out.println("yellow key pressed " + event.getCode()));
}
}