【发布时间】:2018-06-18 02:55:21
【问题描述】:
我在 Netbeans 中有一个标准(非 JavaFX)Maven Java 项目。它应该做的第一件事是加载一个 .fxml 文件,但我似乎无法使用 getClass().getResource() 找到它。
这很不寻常,因为这个项目是从一个标准的 Java 项目中导入的,它运行得很好,没有错误。
这里是主要方法:
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
Main_PanelController controller = new Main_PanelController(this);
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main_Panel.fxml"));
loader.setController(controller);
URL url = getClass().getResource("Main_Panel.fxml");
System.out.println("URL: " + url);
System.exit(0);
Parent root = loader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.getIcons().add(new Image(new FileInputStream(Paths.get("Pictures", "SBU Emblem.png").toFile())));
stage.setAlwaysOnTop(true);
stage.setTitle("Simple Knisley Citation Tool α 0.5");
stage.setResizable(false);
stage.show();
}
该 URL 始终返回为 null。
& 文件层次结构:
我有System.out.println 作为测试方法来查看URL 对象是否返回为空。根据我读到的关于getClass().getResource() 的所有内容,它应该在与调用类相同的包中获取任何对象,Main_Panel.fxml 是。
这是Clean & Build 使用命令jar tf Simple-Knisley-0.5-Alpha-jackofall.jar 运行后target 文件夹中的Jar 文件结构
META-INF/
META-INF/MANIFEST.MF
com/
com/protonmail/
com/protonmail/sarahszabo/
com/protonmail/sarahszabo/simpleknisley/
com/protonmail/sarahszabo/simpleknisley/core/
com/protonmail/sarahszabo/simpleknisley/core/CitationDiskManager.class
com/protonmail/sarahszabo/simpleknisley/core/Main_PanelController.class
com/protonmail/sarahszabo/simpleknisley/core/CitationGenerator$GeneratorType.class
com/protonmail/sarahszabo/simpleknisley/core/CitationGenerator.class
com/protonmail/sarahszabo/simpleknisley/core/Main.class
.netbeans_automatic_build
META-INF/maven/
META-INF/maven/com.protonmail.sarahszabo.simpleknisley/
META-INF/maven/com.protonmail.sarahszabo.simpleknisley/Simple-Knisley/
META-INF/maven/com.protonmail.sarahszabo.simpleknisley/Simple-Knisley/pom.xml
META-INF/maven/com.protonmail.sarahszabo.simpleknisley/Simple-Knisley/pom.properties
我在 Kubuntu 18.04 Bionic Beaver 上的 Netbeans 8.2 上使用 Java 8_171
【问题讨论】:
-
看看这篇文章:stackoverflow.com/questions/3803326/…,我认为这与 Maven 有关,如果我不熟悉,但您可以尝试使用完整路径,例如:
getClass().getResource("/com/protonmail/sarahszabo/simpleknisley/core/Main_Panel.fxml") -
在我之前的推荐中,有很多人在调整 maven 构建路径配置系统或一般设置来解决问题。如果我之前的建议不起作用,请阅读他们的一些答案。
-
我在这个 jar 中没有看到 FXML 文件。为 fxml 文件取消资源文件夹。
-
您是否尝试在资源前添加“/” (
getClass().getResource("/Main_Panel.fxml");)?这是我在使用这种方法时总是落入的陷阱。 -
我不确定这是否是那种项目,但某些项目类型要求您将资源放在单独的“资源树”中,即可能有单独的“其他来源”项在您的项目中,您需要将 fxmls 移动到(并重现正确的包结构)。