首页 > 解决方案 > 无法通过 FXMLLoader 加载 fxml 文件(InvocationTargetException)

问题描述

我第一次尝试将 JavaFx 与 Maven 一起使用。通过这个主题:链接IntelliJ can't identify JavaFX 11 with OpenJDK 11,我配置了项目。但无论我做什么,我都无法加载 fxml 文件,因为“getClass().getResource(path)”返回 null。

我更改了路径,以“/”开头,没有,更改了包,创建了包,删除了包,更改了模块信息中的引用,但这不起作用。

结构:https ://ibb.co/Hhwzk8b

module LogAggregator {
    requires javafx.fxml;
    requires javafx.controls;

    opens fxml to javafx.fxml;
    exports com.github.PavelKisliuk;
}

//------------------------------------------------ ----

public class Main extends Application {
    public void start(Stage primaryStage) throws Exception {

              String path = "fxml/Input.fxml";
              FXMLLoader fxmlLoader = new FXMLLoader();
      fxmlLoader.setLocation(getClass().getResource(path));
      Parent fxmlMainWindow = fxmlLoader.load();

      //start-up window
      //-----------------------------------------------
      Scene s = new Scene(fxmlMainWindow);
      primaryStage.setScene(s);
      primaryStage.show();
  }

  public static void main(String... args) {
      launch(args);
  }
}

可能有人知道这个问题并且可以帮助我。没有maven,我没有任何问题。

决定

这样的路径:

String path = "/fxml/Input.fxml";

加上两个字符串到模块信息:

opens com.github.PavelKisliuk.controller to javafx.fxml;
exports com.github.PavelKisliuk.controller to javafx.fxml;

标签: javamavenjavafx

解决方案


您的 Main 类似乎在包com.gihub.PavelKisliuk中,但资源在fxml。在这种情况下,您使用的相对路径解析为不存在com.gihub.PavelKisliuk/fxml/Input.fxml

解决方案:

  1. 首选:将资源移至“com.gihub.PavelKisliuk”
  2. 将主类移出“com.gihub.PavelKisliuk”

希望这可以帮助...


推荐阅读