Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX 8 How to set program icon to alert?

How can I set program icon to alert without using alert.initOwner()? Why without initOwner? It's because some alert must be shown before whole window is initialized, so there's no scene that I can put to initOwner function.

like image 664
Iks Ski Avatar asked Apr 19 '17 20:04

Iks Ski


2 Answers

You can steal the DialogPane from an Alert instance, and add it to a regular Stage. A Node can only be the root of one Scene at a time, so you need to replace the root of the Alert’s Scene first:

public class AlertWithIcon
extends Application {
    @Override
    public void start(Stage stage) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
            "Are you sure you want to delete this item?",
            ButtonType.YES, ButtonType.NO);
        alert.setHeaderText("Delete Item");

        DialogPane pane = alert.getDialogPane();

        ObjectProperty<ButtonType> result = new SimpleObjectProperty<>();
        for (ButtonType type : pane.getButtonTypes()) {
            ButtonType resultValue = type;
            ((Button) pane.lookupButton(type)).setOnAction(e -> {
                result.set(resultValue);
                pane.getScene().getWindow().hide();
            });
        }

        pane.getScene().setRoot(new Label());
        Scene scene = new Scene(pane);

        Stage dialog = new Stage();
        dialog.setScene(scene);
        dialog.setTitle("Delete Item");
        dialog.getIcons().add(new Image("GenericApp.png"));

        result.set(null);
        dialog.showAndWait();

        System.out.println("Result is " + result);
    }
}
like image 118
VGR Avatar answered Nov 12 '22 08:11

VGR


public class AlertWithIcon
extends Application {
    @Override
    public void start(Stage stage) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
            "Are you sure you want to delete this item?",
        ButtonType.YES, ButtonType.NO);    
       alert.setHeaderText("Delete Item"); 
   ((Stage)alert.getDialogPane().getScene().getWindow()).getIcons().add(new image("GenericApp.png"));
    alert.showAndWait();
}
}
like image 9
ismail Avatar answered Nov 12 '22 08:11

ismail