Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ IDEA - getClass().getResource("...") return null

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

like image 303
BilalDja Avatar asked Oct 12 '14 17:10

BilalDja


4 Answers

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~

like image 184
MewX Avatar answered Nov 15 '22 15:11

MewX


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.

like image 24
stacky Avatar answered Nov 15 '22 16:11

stacky


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.

like image 24
AlwaysLearner Avatar answered Nov 15 '22 14:11

AlwaysLearner


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

like image 3
Max Yan Avatar answered Nov 15 '22 16:11

Max Yan