IntelliJ IDEA - getClass().getResource(“…”) return null

南笙酒味 提交于 2019-11-30 11:01:11

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~

stacky

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.

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

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.

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

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!