Search code examples
javaimageresourcesclassloader

My resource does not load - "Input stream must not be null"


I read ~4 Stackoverflow Posts (1, 2) already, and did everything like it was explained there, but I get a NullPointerException while I try to load an Image.

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Input stream must not be null

My package structure:

packages

Code where I try to load the image:

Image image = new Image(this.getClass().getResourceAsStream("/regexgolf2/ui/img/edit.png"));

I don't understand why It does not work.


Solution

  • Your images are in a package under the src folder. The class loader does not look there for files. The class loader looks for files in your class path.

    In order for getResource to work in your case, you need to put the images in the class path.

    I suggest you copy the image files manually to your build folder (under the same path, e.g. out/regexgolf2/ui/images and run your app again.

    If it works you can start thinking of ways to get the files to the class path (e.g. copy them as part of the build/packaging process or putting them in another folder which is in the class path).