【发布时间】:2017-04-19 20:10:53
【问题描述】:
如何在不使用alert.initOwner() 的情况下将程序图标设置为警报?
为什么没有initOwner?这是因为在整个窗口初始化之前必须显示一些警报,所以我无法将场景放入initOwner函数。
【问题讨论】:
如何在不使用alert.initOwner() 的情况下将程序图标设置为警报?
为什么没有initOwner?这是因为在整个窗口初始化之前必须显示一些警报,所以我无法将场景放入initOwner函数。
【问题讨论】:
您可以从 Alert 实例中窃取 DialogPane,并将其添加到常规 Stage。一个Node一次只能是一个Scene的根,所以需要先替换Alert的Scene的根:
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);
}
}
【讨论】:
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();
}
}
【讨论】:
它是这样完成的:
// 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
【讨论】:
正确的实现是按照上面的cmets:
// 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")));
【讨论】: