我在 JavaFX 中有一个带有 .FXML 文件的应用程序,我在场景中添加了一个按钮。然后我尝试向它添加加速器,但是当它启动时会抛出 NullPointerException。为什么它不起作用以及如何解决这个问题。
@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();
}
});
}
我的 .fxml 非常复杂,因为它包含我的应用程序的整个模块,所以我只粘贴一行带有按钮。该按钮位于工具栏中。
<Button fx:id="addQuickNote" mnemonicParsing="false" onAction="#handlequickNote" prefWidth="77.0" text="Z tekstu" />
我正在加载 .fxml 作为主场景的一部分。我正在通过此代码执行此操作。
try {
panel = FXMLLoader.load(getClass().getResource("Notes.fxml"));
} catch (IOException ex) {
showErrorDialog ....;
}
rightPanel.getChildren().add(panel);
mainPanel.setRight(rightPanel);
最佳答案
正如 user714965 提到的那样,您的场景尚未完全构建,因此 addQuickNote.getScene()
为 null
。
另一种解决方案可能是这样的:
@Override
public void initialize(URL url, ResourceBundle rb) {
Platform.runLater(() -> {
addQuickNote.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN), () -> {
addQuickNote.fire();
});
});
}
关于java - JavaFX 中的按钮加速器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736186/