Button Accelerator in JavaFX

I have an application in JavaFX with the .FXML file, and I add a button to the scene. Then I tried to add an accelerator to it, but when it launches it, it throws a NullPointerException. Why it does not work and how to solve it.

@FXML Button addQuickNote; @FXML public void handlequickNote(ActionEvent e) { String text = SampleController.getSelectedText(); if (text != null) { SampleController.profileManager.insertNote(DataParser.getNote(text)); } } @Override public void initialize(URL url, ResourceBundle rb) { addQuickNote.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN), new Runnable() { @Override public void run() { addQuickNote.fire(); } }); } 

My.fxml is quite complicated because it contains the whole module for my application, so I only insert the row with the button. The button is in the toolbar.

 <Button fx:id="addQuickNote" mnemonicParsing="false" onAction="#handlequickNote" prefWidth="77.0" text="Z tekstu" /> 

I am loading .fxml as part of the main scene. I am doing this with this code.

 try { panel = FXMLLoader.load(getClass().getResource("Notes.fxml")); } catch (IOException ex) { showErrorDialog ....; } rightPanel.getChildren().add(panel); mainPanel.setRight(rightPanel); 
+4
source share
2 answers

I think addQuickNote.getScene() is null because your controls are not fully initialized at this point, and the button just does not have a Scene set.

Solve this without calling addQuickNote.getScene().getAccelerators()... in the initialize method. After initializing the controller in your main method, make another call to your controller to the method in which you initialize your accelerators.


EDIT: Your start method seems incomplete. It should look something like this:

 @Override public void start(Stage primaryStage) throws IOException { FXMLLoader loader = new FXMLLoader(); AnchorPane page = (AnchorPane) loader.load(getClass().getResourceAsStream("MainScene.fxml")); Scene scene = new Scene(page); MainSceneController controller = loader.getController(); controller.initializeAccelerators(); primaryStage.setScene(scene); primaryStage.show(); } 
+3
source

As user714965 mentions that your scene has not yet been fully built, and addQuickNote.getScene() has null . Another solution might be something like this:

 @Override public void initialize(URL url, ResourceBundle rb) { Platform.runLater(() -> { addQuickNote.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN), () -> { addQuickNote.fire(); }); }); } 
+3
source

Source: https://habr.com/ru/post/1482577/


All Articles