JavaFX 8如何设置程序图标以提醒?

时间:2017-04-19 20:10:53

标签: java javafx javafx-8

如何在不使用alert.initOwner()的情况下将程序图标设置为警告? 为什么没有initOwner?这是因为在整个窗口初始化之前必须显示一些警报,所以我没有可以放到initOwner函数的场景。

4 个答案:

答案 0 :(得分:4)

您可以从Alert实例中窃取DialogPane,并将其添加到常规舞台。节点一次只能是一个场景的根,因此您需要先替换Alert场景的根目录:

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);
    }
}

答案 1 :(得分:2)

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();
}
}

答案 2 :(得分:0)

这是如何完成的:

// Get the Stage.
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();

// Add a custom icon.
stage.getIcons().stage.getIcons().add(new Image("images/logo_full3.png"));

上面的图像参考可能有问题。但只要它可以工作,你就可以尝试配置。这是我的方式(我使用maven)。如果你不使用maven,你的可能会有所不同。

完整教程:Alert javafx tutorial

答案 3 :(得分:-1)

正确的实现方法如下:

// Get the Stage.
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();

// Add a custom icon.
stage.getIcons().add(new Image(getClass().getResourceAsStream("images/logo_full3.png")));
相关问题