JavaFX default focused button in Alert Dialog

后端 未结 3 997
轮回少年
轮回少年 2021-02-19 15:19

Since jdk 8u40, I\'m using the new javafx.scene.control.Alert API to display a confirmation dialog. In the example below, \"Yes\" button is focused by default inste

3条回答
  •  面向向阳花
    2021-02-19 15:37

    I am not sure if the following is the way to usually do this, but you could change the default button by looking up the buttons and setting the default-behavior yourself:

    public boolean showConfirmDialog(String title, String header, String content, AlertType alertType) {
        final Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
    
        alert.getButtonTypes().clear();
        alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
    
        //Deactivate Defaultbehavior for yes-Button:
        Button yesButton = (Button) alert.getDialogPane().lookupButton( ButtonType.YES );
        yesButton.setDefaultButton( false );
    
        //Activate Defaultbehavior for no-Button:
        Button noButton = (Button) alert.getDialogPane().lookupButton( ButtonType.NO );
        noButton.setDefaultButton( true );
    
        final Optional result = alert.showAndWait();
        return result.get() == ButtonType.YES;
    }
    

提交回复
热议问题