javafx Default and Cancel Buttons


Example

Button API provides an easy way to assign common keyboard shortcuts to buttons without the need to access accelerators' list assigned to Scene or explicitly listening to the key events. Namely, two convenience methods are provided: setDefaultButton and setCancelButton:

  • Setting setDefaultButton to true will cause the Button to fire every time it receives a KeyCode.ENTER event.

  • Setting setCancelButton to true will cause the Button to fire every time it receives a KeyCode.ESCAPE event.

The following example creates a Scene with two buttons that are fired when enter or escape keys are pressed, regardless whether they are focused or not.

FlowPane root = new FlowPane();
        
Button okButton = new Button("OK");
okButton.setDefaultButton(true);
okButton.setOnAction(e -> {
    System.out.println("OK clicked.");
});
        
Button cancelButton = new Button("Cancel");            
cancelButton.setCancelButton(true);
cancelButton.setOnAction(e -> {
    System.out.println("Cancel clicked.");
});
        
root.getChildren().addAll(okButton, cancelButton);
Scene scene = new Scene(root);

The code above will not work if these KeyEvents are consumed by any parent Node:

scene.setOnKeyPressed(e -> {
    e.consume();
});