在 JAR 中使用 loader.setLocation(getClass().getClassLoader() 加载



我正在尝试加载我的 *.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

如此处所述,我使用以下语句来加载 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文件移动到资源文件夹(如此处所述,因为我认为应该可以访问现在所在的文件。

将其添加到您的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());`

最新更新