JavaFX default focused button in Alert Dialog

后端 未结 3 1014
轮回少年
轮回少年 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:33

    A simple function thanks to crusam:

    private static Alert setDefaultButton ( Alert alert, ButtonType defBtn ) {
       DialogPane pane = alert.getDialogPane();
       for ( ButtonType t : alert.getButtonTypes() )
          ( (Button) pane.lookupButton(t) ).setDefaultButton( t == defBtn );
       return alert;
    }
    

    Usage:

    final Alert alert = new Alert( 
             AlertType.CONFIRMATION, "You sure?", ButtonType.YES, ButtonType.NO );
    if ( setDefaultButton( alert, ButtonType.NO ).showAndWait()
             .orElse( ButtonType.NO ) == ButtonType.YES ) {
       // User selected the non-default yes button
    }
    

提交回复
热议问题