I have a NetBeans project. In the project directory, I’ve created some additional directories for keeping resources (images). So the path of one of my images is “/res/imgs/on.png” (“res” and everything in it is created by me). Then I’ve added the “res” directory to my project’s sources (Right-click on my project in NetBeans -> Properties -> Sources -> Add Folder (for Source Packages Folder section)). And I’ve accessed to the URL of the image in my project using the following code:
URL url = Class.class.getResource("/imgs/on.png");
And this was successful – just a few days ago. Today, after this code execution, url variable was set to null. But when the code was modified to this:
URL url = Class.class.getResource("/imgs");
The (url != null) was true.
Next, I’ve created a yet another project, where I’ve done exactly the same manipulations (that is, created subdirectories in the project folder, loaded some files to it and tried to execute a code, similar to these I’ve written above). And these manipulations were successful. After that, I’ve returned to my first project (that initialized url to null when tried to access “/imgs/on.png”). And it turned out, that everything was again OK there and the image’s URL loaded successfully…
So, the question is, what was the problem? Is this a NetBeans bug, or maybe I’m doing something in a wrong way?
Probably by some Netbeans compile/clean glitch, the “on.png” was not in the classes directory and therefore was not found on the classpath. After a restart or any operation that would cause Netbeans to rescan the source folders, it was back there.
By the way instead of
Class.class.getResource()you should use the caller’s class, e.g.this.getClass().getResource()to use the same class loader.