JavaFX. FXML加载程序无法在带有模块的项目中找到.fxml文件

问题描述:

我有一个结构如下的项目:

I have a project with such structure:

我试图使用以下代码从Main类加载sample.fxml:

I trying to load sample.fxml from the Main class using this code:

Parent root = FXMLLoader.load(Main.class.getResource("../../submodule/src/java/sample.fxml"));

但是它不起作用. sample.fxml文件代码为:

but it doesn't work. The sample.fxml file code is:

<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>


<GridPane fx:controller="sample.Controller"
      xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10"    vgap="10">
</GridPane>

问题在于FXML加载器找不到此位置.该怎么解决?

The problem is that FXML loader can't find this location. How to solve it?

我建议遵循以下基本的maven包结构:

I would suggest to follow the basic maven package structure, like this:

src
 |--main
      |--java
      |--resource (put your FXML file into this folder)

那么以下方法应该起作用:

Then the following should work:

Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("sample.fxml"));

您还可以将FXML文件放入子文件夹:

You can also put your FXML file into a subfolder:

... = FXMLLoader.load(getClass().getClassLoader().getResource("layouts/sample.fxml"));