How do you set the icon of a Dialog control Java FX/Java 8

后端 未结 4 2084
臣服心动
臣服心动 2021-02-07 05:15

I might be missing something very obvious, but I can\'t find out how to set the Icon for a Dialog component (ProgressDialog to be more precise). I know how to do that for a Stag

4条回答
  •  我在风中等你
    2021-02-07 05:36

    This is a method that I include in my JavaFX projects, simply calling this method and passing the Alert as a parameter will set both the title bar icon and the header graphic.

    public class Msg {
    
    public void showInfo(String title, String header, String message) {
        Alert alertShowInfo = new Alert(Alert.AlertType.INFORMATION);
        addDialogIconTo(alertShowInfo); //add icon and header graphic
        alertShowInfo.setTitle(title);
        alertShowInfo.setHeaderText(header);
        alertShowInfo.setContentText(message);
        alertShowInfo.showAndWait();
    }
    
    //this adds images to Alert
    public void addDialogIconTo(Alert alert) {
        // Add custom Image to Dialog's title bar
        final Image APPLICATION_ICON = new Image("icon.png");
        Stage dialogStage = (Stage) alert.getDialogPane().getScene().getWindow();
        dialogStage.getIcons().add(APPLICATION_ICON);
    
        // Add custom ImageView to Dialog's header pane.        
        final ImageView DIALOG_HEADER_ICON = new ImageView("icon.png");
        DIALOG_HEADER_ICON.setFitHeight(48); // Set size to API recommendation.
        DIALOG_HEADER_ICON.setFitWidth(48);
        alert.getDialogPane().setGraphic(DIALOG_HEADER_ICON);                       
        }
    }
    

    Then, in whatever class I wish to use the Alert, it will already have the customized icon and header graphic.

    public static void main(String[] args){
            Msg msg = new Msg();
    
            // Alert will now include custom icon and header graphic.
            msg.showInfo("Sucess!", "Program succeeded", "Now exiting program");
    } 
    

提交回复
热议问题