Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accelerator for Button in JavaFX

Tags:

java

javafx-2

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);
like image 214
Kaa Avatar asked May 24 '13 13:05

Kaa


People also ask

How do I program a button in JavaFX?

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.

How do I resize a button in JavaFX?

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.

How do you make a button invisible in JavaFX?

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 .


1 Answers

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();
        });
    });
}
like image 62
Terran Avatar answered Sep 19 '22 01:09

Terran