44

I'm using IntelliJ IDEA 13.1.5, I used to work with Eclipse. I'm working on JavaFX application, I try to load FXML file within my MainApp class using getClass().getResource(). I read the documentation and I try several idea, at the end I have null.

This is the hierarchy :

dz.bilaldjago.homekode.MainApp.java

dz.bilaldjago.homekode.view.RootLayout.FXML

This is the code snippet I used:

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/RootLayout.fxml"));

I tried other solution such giving the url from the root and using the classLoader

the result is the same. Any idea please

BilalDja
  • 1,072
  • 1
  • 9
  • 17
  • 3
    possible duplicate of [Java - class.getResource returns null](http://stackoverflow.com/questions/4301329/java-class-getresource-returns-null) – maja Apr 11 '15 at 18:23

15 Answers15

29

I solved this problem by pointing out the resource root on IDEA.

Right click on a directory (or just the project name) -> Mark directory As -> Resource Root.

Recompile & rejoice :P Hope this working for you~

MewX
  • 4,232
  • 1
  • 29
  • 38
  • 1
    did not work for me, i changed the Compiler resource patterns. Made the resource folder both as the root folder of my project and then the working folder where my Class is and still didn't work! please help. I am using intellij – Metin Dagcilar Dec 20 '17 at 00:11
  • @AVERAGE Hi, I don't think that would be a problem. Have you tried re-creating a project, and redo your operation? If it still doesn't work, please post your detailed operation steps. That would be helpful for solving your issue. – MewX Dec 28 '17 at 10:25
  • for me, it worked if it's "src/resources" next to "src/main" path, but got null if in "resources" path – BingLi224 Jan 25 '20 at 04:24
  • My sample program start working and that sample "HELLO" window is appearing but even though now the error is still there i.e->"Argument 'getClass().getResource("sample.fxml")' might be null" – Pranshu_Taneja Jun 27 '21 at 06:40
25

For those who use Intellij Idea: check for Settings -> Compiler -> Resource patterns.

The setting contains all extensions that should be interpreted as resources. If an extension does not comply to any pattern here, class.getResource will return null for resources using this extension.

maja
  • 17,250
  • 17
  • 82
  • 125
stacky
  • 800
  • 6
  • 18
25

TL; DR;

  1. Put your resources in resources folder.

  2. Use them with one slash before their names: getClass().getResource("/myfont.ttf");

Long Story;

If you are using Intellij IDEA and you created a Maven project, you should put your resources in resources folder (as marked as resource root by intellij itself) and these resource go to the root of your compiled app.

I mean, /resources/myfont.ttf will go to /myfont.ttf in the resulting build.

So you should get it via /myfont.ttf and not myfont.ttf. Use it like this:

getClass().getResource("/myfont.ttf");

No need to change anything else. Just this one helped me.

Community
  • 1
  • 1
AlwaysLearner
  • 443
  • 5
  • 8
4

if your project is a maven project, check the target code to see whether your .fxml file exist there. if it's not there ,just add

<resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>

in your pom.xml

Max Yan
  • 41
  • 3
4

first, you need to set src and resource folders for IntelliJ.

see the icon near the java(blue) and resources(yellow 4 lines) folder.

enter image description here

right-click on java folder and select sources root enter image description here

and right-click on java folder and select resource root enter image description here

after that create the same package in the java folder and resource folder.

for example: packages -> org.example enter image description here

├─ src
   ├─ main
       ├─ java
       |  └─ com
       |      └─ example
       |           └─ A.class
       |
       └─ resources  
          └─ com
              └─ example
                    └─ fxml
                         └─ AFXML.fxml

in A.class you can use this.

Java

 FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/AFXML.fxml"));
 Parent root = loader.load();

Kotlin

 val loader = FXMLLoader(javaClass.getResource("fxml/AFXML.fxml"))
 val root = loader.load<Parent>()

or

 val loader = FXMLLoader(A::class.java.getResource("fxml/AFXML.fxml"))
 val root = loader.load<Parent>()
Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78
2

Very frustrating. What also happens is that the directory containing the resources are sometimes created as:

 └── resources
     └── my.tests             
           ├── t1.txt
           └── t2.txt

instead of:

 └── resources
     └── my
          └── tests
              ├── t1.txt
              └── t2.txt

The solution is to just manually recreate the directory structure so that it resembles the second example.

I also recommend to to troubleshoot your tests on the command line (with mvn clean test) if you're using maven to eliminate the chances of this being an IDE issue.

Jaco Van Niekerk
  • 4,180
  • 2
  • 21
  • 48
  • 1
    Another pitfall of IntelliJ, if you try to create directory structure as explained above, is that IntelliJ will automatically convert them to package structure (my.tests). This happens in IntelliJ's default view - Project view. The only way to create directories under resources is to switch to the Project Files view. Only then you are able to crate a proper directory structure... – caytekin Sep 15 '22 at 08:48
1

If your project is Gradle, check Settings -> Build, Execution, Deployment -> Gradle -> Build and run section. Ensure that "Build and run using" option is "Gradle".

Intellij IDEA's compiler doesn't copy "resources" to build dir nor to tests classpath. Also, it unexpectedly uses dummy "out" dir instead of "build".

UPDATED: only 1 option "Build and run using" is enough to set to Gradle.

kinORnirvana
  • 1,667
  • 2
  • 17
  • 22
1

In my case, ClassLoader helped

Class testClass = getClass();
URL url = testClass.getClassLoader().getResource(/fileName);
Сергей
  • 111
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 25 '22 at 08:54
  • Furthermore, there must not be a `/` at the beginning of `fileName`. – koppor Nov 06 '22 at 15:34
0

As per suggestion, updated answer.

Step-1

  1. Right click on project
  2. Click on Mark Directory as
  3. Click on Sources Root

Step-2

  1. Click on File in Menu Bar
  2. Click on Project Structure… to open settings panel

Step-3

  1. Click on Modules tab
  2. As you see there isn’t any resources folder added as Content Root
  3. We need to add resources folder into it

Step-4

  1. Make sure to click on resource folder
  2. Click on Resources tab after that
  3. You will see resources folder added as Resource Folders in right panel

Re-run your java program and now it should work.

<---Previous Answer---->

Fixed similar issue today by adding resources folder into Resource Tab in IntelliJ IDE

Hope this helps. Also, details tutorial.

  • 1
    Thanks for answering, I don't proved if it's the correct answer ;) Linking images is not a well seen behaviour on stackoverflow. Can you describe what you have done? Perhaps in a list style: 1.) click here 2.) press the button or arrow style "ressources->edit" – nologin Feb 08 '20 at 17:54
  • 1
    Thanks for suggestion @nologin - I'm new to stackoverflwo community.. Updated answer. –  Feb 09 '20 at 18:13
0

In Project Structure > Project you have to make sure Project compiler output: has its value filled in. In my case it did not. Point it to the ./target or ./bin (whatever you have) directory in your project.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Dion
  • 78
  • 1
  • 9
0

I used below code to access the file from resource folder in spring application. I used classLoader.getResourceAsStream(FileName) instead of getClass().getResourceAsStream(FileName), Hope this would help to access the file residing in resource folder.

String fileName = "./file.txt";
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileName);

I resolved file access so thought to share with all .
0

I had this same problem and tried all of the answers to this post. I finally found an answer on a different forum that works. This was the code I put into the build section of pom.xml

<resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>

It is important to make sure the directory section is the directory of the resource class, not the main class.

I also changed my compiler settings as was suggested in another comment. I found this answer on a post here: https://javawithus.com/en/classloadergetresource-returns-null/

-1

Windows is case-sensitive, the rest of the world not. Also an executable java jar (zip format) the resource names are case sensitive.

Best rename the file

view/RootLayout.FXML

to

view/RootLayout.fxml

This must be done by moving the original file away, and creating a new one.

Also compile to a jar, and check that the fxml file was added to the jar (zip file). When not IntelliJ resource paths are treated by an other answer.

By the way this is path relative to the package path of getClass(). Be aware if you extended this class the full path changes, better use:

MainApp.class.getResource("view/RootLayout.fxml")
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
-1

Use this syntax:

("../view/RootLayout.fxml"))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
-2

I gave up trying to use getClass().getResource("BookingForm.css"));

Instead I create a File object, create a URL from that object and then pass it into getStyleSheets() or setLocation() File file = new File(System.getProperty("user.dir").toString() + "/src/main/resources/BookingForm.css");

scene.getStylesheets().add(folder.toURI().toURL().toExternalForm());

Metin Dagcilar
  • 524
  • 4
  • 16