简体   繁体   中英

FXML loader can't find .fxml file in the project with modules

I have a project with such structure:

在此处输入图片说明

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?

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

Here is a link showing the difference between getClass().getResource() vs getClass.getClassLoader().getResource() (The difference is in relative vs absolute paths. If you always want to start from the /resources directory in a Maven project, you should use getClass().getClassLoader().getResource() .

What is the difference between Class.getResource() and ClassLoader.getResource()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM