【问题标题】:JavaFX error-dialog doesn't show up in runnable jar file because of changed graphic由于图形更改,JavaFX 错误对话框未显示在可运行的 jar 文件中
【发布时间】:2018-06-09 14:27:45
【问题描述】:

我创建了一个 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*/
    }

}

【问题讨论】:

  • */Image-path*/ 是您代码中某种形式的编辑的真实路径吗?
  • 不,真正的路径是“src/Images/image.png”
  • 您的 jar 不太可能包含名为 src 的文件夹。使用 zip 工具检查内容。
  • src 文件夹实际上不是 jar 文件的一部分,但它包含图像文件夹,因此我将路径更改为 "Images/image.png"。但这也无济于事

标签: java javafx jar imageview alert


【解决方案1】:

按如下方式创建图像:

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

它使用ImageView(String url) 构造函数,它将为您加载Image。由于Images 文件夹位于jar 内,getResource 将返回该文件的“特殊”URL。您不能将它作为文件引用,因为 JAR 是包含图像的单个文件,没有单独的图像文件。

【讨论】:

  • 非常感谢,这对我有用。但我不能使用getClass(),因为我的方法是static,所以我使用我的GUIclass.class 而不是getClass(),效果很好。
猜你喜欢
  • 1970-01-01
  • 2016-07-13
  • 2021-08-15
  • 1970-01-01
  • 2016-02-09
  • 2022-11-07
  • 2019-10-31
  • 1970-01-01
  • 2020-05-18
相关资源
最近更新 更多