We're going to look at loading resources in Java in the Eclipse IDE, though the basic principles are the same in whatever IDE you're using. The general idea is to use the classloader to load your resources rather than using a File object or a FileInputStream. This makes your applications more flexible and relocatable and makes resource loading independent of the current directory.
The first thing to do is to create two packages: one as our code package root and one for resources:
First the first code package of the root:
And now the resources package:
We import the image 'tj-logo.png' as a resource in the package 'resources'. This can be seen in the image below. We then add some source code (in this case by import from the filesystem):
Now we add an ImageIcon. We address the resource from the package root ('/') and use getResource so that it uses the classloader.
Now we run the application, and we can see if finds the resource:
Having said all that, it's important to adopt a proper build system, irrespective of whichever IDE you use. In practice, this means either Maven or Gradle and in both cases there, the location of resources should be /src/main/resources. This makes things a lot more straightforward.