By Alvin Alexander. Last updated: February 4, 2018
This code for creating a JavaFX menubar and handling a keystroke/key-combination didn’t work as desired, but I think it’s on the right track:
val menuBar = new MenuBar val editMenu = new Menu("Edit") val findMenuItem = new MenuItem("Find") findMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F, KeyCombination.META_DOWN)) findMenuItem.setOnAction((e: ActionEvent) => { println("GOT A COMMAND-F") }) editMenu.getItems.addAll(findMenuItem) menuBar.prefWidthProperty().bind(mainStage.widthProperty()) mainGridPane.getChildren.add(menuBar) root.setTop(menuBar)
In this code the root element is a BorderPane
instance. I’m abandoning this approach because I really don’t want a JavaFX menubar in my application, but I think if I managed the BorderPane
properly it would have worked. (Note that the code shown is written in Scala, but it easily translates to Java.)