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

7

如何在不使用 alert.initOwner() 的情况下设置程序图标进行警报? 为什么不用 initOwner 呢?因为有些警报必须在整个窗口初始化之前显示,所以我无法在 initOwner 函数中放置场景。

4个回答

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

9
你可以从提示框实例中偷取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);
    }
}

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 教程


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接