JavaFX. FXML loader can't find .fxml file in t

2019-08-30 03:51发布

I have a project with such structure:

enter image description here

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"));

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>

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

1条回答
欢心
2楼-- · 2019-08-30 04:12

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"));

You can also put your FXML file into a subfolder:

... = FXMLLoader.load(getClass().getClassLoader().getResource("layouts/sample.fxml"));
查看更多
登录 后发表回答