由于图形更改,JavaFX 错误对话框未显示在可运行的 jar 文件中

JavaFX error-dialog doesn't show up in runnable jar file because of changed graphic

我制作了一个 JavaFX 错误对话框并更改了默认图像。

一开始这看起来不错,但是当我将项目导出为可运行的 *.jar 时,这个对话框就不再出现了。

我想,当我离开图像时一切正常,但这不是我的解决方案。

代码

public static void alert() throws IOException {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("FATAL ERROR");
    alert.setHeaderText("/*Error message*/");

    ImageView alertImage = new ImageView(new Image(new FileInputStream(new File("*/Image-path*/"))));   
    alert.setGraphic(alertImage);

    alert.setContentText("/*query*/");

    //Button funktions
    Optional<ButtonType> result = alert.showAndWait();

    if (result.isPresent() && (result.get() == ButtonType.OK)) {
        /*unimportant code*/
    }

    if (result.isPresent() && (result.get() == ButtonType.CANCEL)) {
        /*unimportant code*/
    }

}

按如下方式创建您的图像:

ImageView alertImage = new ImageView(getClass().getResource("/Images/image.png").toExternalForm());   

它使用 ImageView(String url) 构造函数,它将为您加载 Image。由于 Images 文件夹位于 jar 中,因此 getResource 将 return 一个 'special' URL 到该文件。您不能将它作为 作为 文件引用,因为 JAR 是包含图像的单个文件,没有单独的图像文件。