【问题标题】:Load FXML with loader.setLocation(getClass().getClassLoader() within a JAR在 JAR 中使用 loader.setLocation(getClass().getClassLoader() 加载 FXML
【发布时间】:2018-03-15 01:53:02
【问题描述】:

我正在尝试加载我的 *.fxml 文件,这些文件位于不同的包中,打包在 JAR 中。

我的文件夹结构:(所有文件夹都在类路径中)

- src/main/java: 
    - com.test.controller
        - Application.java
    - com.test.view
        - Main.fxml
- src/main/test: contains unit tests
- src/main/resources: contains images

here 所述,我使用以下语句加载 FXML 文件。 (不带前导斜杠“/”)该方法在Application.java 文件中调用。

FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("com/test/Main.fxml")

如果我在 Eclipse 中运行项目,这工作得很好,但如果我执行 JAR(使用 Gradle 创建),则会失败并显示 java.lang.IllegalStateException: Location is not set

如果我解压JAR文件,我可以看到/com/test/下的Main.fxml,所以文件确实存在。

我尝试了几种访问不同包中的 FXML 文件的变体,但没有任何效果。有人知道在这里做什么吗?

我宁愿不将 FXML 文件移动到资源文件夹(如 here 所述,因为我认为应该可以访问它们现在所在的文件。

【问题讨论】:

    标签: jar classpath fxml


    【解决方案1】:

    将此添加到您的 build.gradle(如果您使用 Gradle 作为构建工具)

    sourceSets {
        main {
            resources {
                srcDirs = ["src/main/java", "src/main/resources"]
            }
        }
    }
    

    然后加载资源如下:

    选项1:相对于当前类文件(MyClass):

    MyClass.class.getResource("../view/Main.fxml")
    

    选项2:相对于类路径根

    URL configUrl = MyClass.class.getClassLoader().getResource("config.xml");
    File myConfigFile = new File(configUrl.toURI());`
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 2017-08-12
      • 1970-01-01
      相关资源
      最近更新 更多