2

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
bvl
  • 161
  • 2
  • 12
  • Move the FXML file into the _resources_ directory. Then using `getClass().getResource("/sample.fxml")` should work—assuming both modules end up on the classpath at runtime. – Slaw Mar 18 '19 at 16:16
  • @Slaw Unfortunately it didn't help. – bvl Mar 18 '19 at 16:49
  • 2
    Your project structure looks a bit strange. Is your main module a maven parent? – Samuel Philipp Mar 18 '19 at 19:56
  • moduls or not: class.getResource(...) _does not_ support _".."_ - actually, I don't understand why everybody seems to assume that it does - just read the api doc and what do you _not_ see ;) – kleopatra Mar 20 '19 at 09:30

1 Answers1

1

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()?

Nexonus
  • 706
  • 6
  • 26