如何在不使用 alert.initOwner()
的情况下设置程序图标进行警报?
为什么不用 initOwner
呢?因为有些警报必须在整个窗口初始化之前显示,所以我无法在 initOwner
函数中放置场景。
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();
}
}
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);
}
}
这就是它的实现方式:
// 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 教程
正确的实现是遵循上面的注释:
// 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")));