1

I have a JavaFX project with Gradle built tool. What is the right way to construct the src/main/resources folder so that I could easily access the *.fxml and *.css by simple line of code:

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


I'm using the Gradle plugin and build.gradle file for JavaFX in this tutorial, It has a simple project tree like this:

.
├── src.main
|    ├── java
|    |   ├── org.openjfx
|    |   |   ├── MainApp.java
|    |   └── └── FXMLController.java
|    ├── resources
|    |   ├── org.openjfx
|    |   |   ├── scene.fxml
└──  └── └── └── styles.css

In this way, the MainApp.java can load scene.fxml using getResource("scene.fxml").


However, if the java and the resources directory structures doesn't match, suppose my project tree like this so that I could separate the fxml file and css file:

.
├── src.main
|    ├── java
|    |   ├── org.openjfx
|    |   |   ├── anotherPackage 
|    |   |   |   ├── MainApp.java
|    |   └── └── FXMLController.java
|    ├── resources
|    |   ├── org.openjfx
|    |   |   ├── layouts
|    |   |   |   ├── scene.fxml
|    |   |   ├── styles
└──  └── └── └── └──styles.css

Now the MainApp.java have to load scene.fxml with getResource("../layouts/scene.fxml")


I am new to Gradle and JavaFX, and I want to know what is the right way to manage the resources including fxml, CSS, as well as pictures, etc.


ps. Sorry if I'm not asking the question correctly.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
wiio_12
  • 96
  • 1
  • 7
  • 3
    Note: Don't use `..` when accessing resources via `getResource`. – Slaw Apr 20 '19 at 19:33
  • 1
    It's really up to you how you want to organize your resources. I've seen projects with all FXML files in `fxml` and all CSS files in `styles`, both at the root of the classpath. Personally, I prefer to put my FXML files and CSS files in the same package as the class that uses them (FXML files, by their nature, tend to be highly coupled with one class). In other words, I tend to mirror my package structure in the resources directory. For other resources (e.g. images), it depends on how they're used; organize them how you think is best for your project. – Slaw Apr 20 '19 at 19:43
  • Thanks, Slaw, It helps a lot. I found [this answer](https://stackoverflow.com/questions/19602727/how-to-reference-javafx-fxml-files-in-resource-folder?rq=1) that solve my problem perfectly. – wiio_12 Apr 21 '19 at 14:42

1 Answers1

1

iirc, the resource directory structure should mirror the package structure. take a look at https://www.eviltester.com/2017/12/resource-files-for-tests-java-maven.html

Ray Tayek
  • 9,841
  • 8
  • 50
  • 90