运行项目与运行应用程序文件时出现 Windows10 Netbeans FXMLLoader 错误

问题描述

我很抱歉,因为有人理解这个问题经常被问到。但是,我的问题有一个我无法解决的警告。

简而言之,我的 Netbeans 11.1 IDE 无法在运行项目时加载 FXML 资源(例如按下运行按钮或使用 f6),但确实加载资源并在运行时运行右键单击并运行应用程序主类 Java 文件 (JavaFXApplication3.java)。

我想通过 IDE 运行项目以便访问 GC Profiler。

我当前的项目层次结构:

src
  |
  app
     |-application
     |           |-JavaFXApplication3.java
     |
     |-views
     |     |-MainMenuFXML.fxml
     |     |-DemoContentFXML.fxml
     |
     |
     |-backups,defaults,controllers,misc packages,etc....

我的应用程序 main 方法从 MainMenuFXML.fxml 加载整个界面。

@Override
public void start(Stage stage) throws Exception{
   Parent root;
   //URL fxmlURL = getClass().getClassLoader().getResource("MainMenuFXML.fxml"); 
   URL fxmlURL = getClass().getClassLoader().getResource("\\app\\views\\MainMenuFXML.fxml");  //returns null when running project

   if(fxmlURL != null){  //runs without error when right clicking and running JavaFXApplication.java file

     Logger.getGlobal().log(Level.INFO,"attempting static load from URL");
     root = FXMLLoader.load(fxmlURL);// Generates java.lang.IllegalStateException: Location is not set.

   }  else {                 

     Logger.getGlobal().log(Level.INFO,"attempting load from new object");
     FXMLLoader loaderMain = new FXMLLoader(getClass().getClassLoader().getResource("\\app\\views\\MainMenuFXML.fxml"));
     root = (Parent)loaderMain.load();   //at this point,the code will always throw an exception

   }
                
   Scene scene = new Scene(root); //GUI entry point
   mainWindow.setScene(scene);
   mainWindow.show();
}

据我所知,在 Netbeans 中运行一个项目会在 C:...\JavaFXApplication\dist\runXXXXXXXXXX 中生成一个可执行文件。在尝试使用 FXMLLoader 加载资源时,以这种方式运行我的代码总是会生成非法参数异常。

 [java] Caused by: java.lang.RuntimeException: Exception in Application start method
     [java]     at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
     [java]     at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
     [java]     at java.lang.Thread.run(Thread.java:748)
     [java] Caused by: java.lang.IllegalStateException: Location is not set.
     [java]     at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434)
     [java]     at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
     [java]     at app.javafxapplication3.JavaFXApplication3.start(JavaFXApplication3.java:102)

...
...
101: FXMLLoader loaderMain = new FXMLLoader(getClass().getClassLoader().getResource("\\app\\views\\MainMenuFXML.fxml"));
102: root = (Parent)loaderMain.load();
...
...

在目录中运行单个文件时,我的猜测是 Netbeans 编译并运行本地存在项目文件的任何文件

通过单文件运行方法运行应用程序总是成功加载资源并运行 GUI。

对于刚开始使用 IDE,我深表歉意。 \dist\ 目录中构建的可执行文件怎么可能无法定位和加载任何这些 FXML 文件

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)