I have an app in JavaFX with .FXML file and i add a button to the scene. Then i tried to add accelerator to it but when it launches it throws NullPointerException. Why it doesn't work and how to solve this.
@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 pretty complicated because it contains whole module for my app so i paste only a line with the button. The button is placed in the ToolBar.
<Button fx:id="addQuickNote" mnemonicParsing="false" onAction="#handlequickNote" prefWidth="77.0" text="Z tekstu" />
I'm loading .fxml as a part of main scene. I'm doing this by this code.
try {
panel = FXMLLoader.load(getClass().getResource("Notes.fxml"));
} catch (IOException ex) {
showErrorDialog ....;
}
rightPanel.getChildren().add(panel);
mainPanel.setRight(rightPanel);
You can create a Button by instantiating the javafx. scene. control. Button class of this package and, you can set text to the button using the setText() method.
Button SizeThe methods setMinWidth() and setMaxWidth() sets the minimum and maximum width the button should be allowed to have. The method setPrefWidth() sets the preferred width of the button. When there is space enough to display a button in its preferred width, JavaFX will do so.
You can use the setVisible() as stated by @Idos. You need to initially set the visibility of the Browse button to false and on the action of Login button toggle the visibility to true .
As user714965 mentionend your Scene was not constructed fully yet and therefor addQuickNote.getScene()
is 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();
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With