My resource does not load - "Input stream must not be null"
Solution 1
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).
Solution 2
In the case of a netbeans maven javaFX project, the resource (img folder) must be in the resources folder:
Then you can load the resource, for example:
Image escribir = new Image(getClass().getResourceAsStream("/img/login.png"));
Related videos on Youtube
quantumbyte
Updated on July 08, 2022Comments
-
quantumbyte almost 2 years
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:
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.
-
BitNinja almost 10 yearsIs image a
java.awt.Image
?
-
-
quantumbyte almost 10 yearsThanks! This fixed the problem and some other similar problems I had with images not loading from fxml files. How can I put them in a folder that is in the classpath / copy them as part of the build process? (I believe I should use something like Ant or Maven, would that fix it?)
-
daramasala almost 10 yearsyes, you can copy/package them using Ant or Maven. If you're using an IDE to build your app, then the IDE probably has some configuration to copy files during build. The general practice is to keep a separate folder for resources that are not source files. After you play around with these concepts you try googling for 'java standard directory structure'.
-
quantumbyte almost 10 yearsI will definitely look into that, I thought the location I put them is fairly common, but what would you recommend? Something like res/images/edit.png?
-
daramasala almost 10 yearsThis is fine. You can leave the more advanced stuff (maven, standard dir structure) for when you want to package/distribute your app.