代码之家  ›  专栏  ›  技术社区  ›  Sarah Szabo

maven javafx项目无法使用getresource找到fxml文件?

  •  2
  • Sarah Szabo  · 技术社区  · 6 年前

    我在NETBeBes中有一个标准的(非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 .

    &文件层次结构:

    Hierarchy

    我有 System.out.println 作为测试方法,查看url对象是否返回为空。根据我所读到的一切 getClass().getResource() 它应该得到与调用类在同一个包中的任何对象, Main_Panel.fxml 是。

    下面是来自 target 文件夹后 Clean & Build 已使用命令运行 jar tf Simple-Knisley-0.5-Alpha-jackofall.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
    

    我在Kubtuu 18.04 Bionic Beaver上使用NETBeaS 8.2的Java8Y171

    1 回复  |  直到 6 年前
        1
  •  2
  •   John Farrelly    6 年前

    这里有一些问题。

    1. Maven希望(默认情况下)资源位于 src/main/resources 目录。它只会复制Java文件。 src/main/java 默认情况下。所以移动你的 fxml 文件到 src/main/resources/com/protonmail/sarahszabo/simpleknisley/core/Main_Panel.fxml

    2. getClass().getResource() 希望您提供要加载的资源的完整路径。所以在你的情况下: getClass().getResource("/com/protonmail/sarahszabo/simpleknisley/core/Main_Panel.fxml")

    使用 getClass().getClassLoader().getResource() 允许您指定要加载的资源的位置,作为调用该资源的类的相对路径:

    getClass().getClassLoader().getResource("Main_Panel.fxml")