How to use getClass().getResource() method - java

When I create ImageIcon class objects I use the following code:
iconX = new ImageIcon (getClass().getResource("imageX.png"))
The above code works correctly either in an applet or a desktop app when the .png is in the same folder of the class.
The question is: how to avoid a NullPointerException when the .Png is in another folder? Or how load the image in the object ImageIcon when it is in a different location to the class?
I don't understand how this method works, if anyone can help me I appreciate it. Thanks!!

Take a look at this - Class#getResource(java.lang.String)
Please click the link above and read the docs and follow to understand what's going on.
It says -
If the name begins with a '/', then the absolute name of the resource is the portion of the name following the '/'.
and
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.'.
So, if this object (where you call getResource) is in package /pkg1 (/ meaning pkg1 is right under the root of the classpath) and you used "imageX.png" then the result would be pkg1/imageX.png which is correct because that's where the image is located at.
But, if we moved the resource (imageX.png) to some other package /pkg2 and you called the method same way then the result would still be pkg1/imageX.png but this time it would be incorrect because the resource is actually located in /pkg2. That's when you end up with NPE.
It's good to explicitly specify the full path of the resource starting from the root of the classpath. (e.g. "/pkg/imageX.png").
Hope this helps.

Simply supply the path to the resource.
So, if you put the image in "/resources/images" within your Jar, you would simply use
iconX = new ImageIcon(getClass().getResource("/resources/images/imageX.png"))
Essentially what you're saying is, class loader, please search your class path for the following resource.

If the image is internal (you want a location relative to your project, or perhaps packaged into your jar), do what mad programmer said:
iconX = new ImageIcon(getClass().getResource("/path/imageX.png"))
The path is relative, so path/ will be a folder in the same folder as your project (or packaged into your jar).
If you want an external image, simply hand ImageIcon constructor the path (ex. "C:/.../file.png"). This isn't recommended though, as it's better to use it as a resource.
For more info on the ImageIcon constructor, see here. for more info on loading class resources, see here (Javadoc links)

Related

Adding/Loading an image in java

I am trying to load an image to display on the screen (just to get an idea of how to do it).
The problem is that when the program tries to load "apple.png" (which is saved on my desktop), it cannot find the image - Where do image files need to be stored in order for them to be found? Here is my loading method:
private void loadImage() {
ImageIcon appleIcon = new ImageIcon("apple.png");
Image appleImage = appleIcon.getImage();
}
If you want to reach it from the desktop, you should use the complete path. The easiest way to handle resources would be to create a folder in you java project, which you can access via "folderName/fileName.example".
Using the full path is an option
C:\filefolder\file.jpg
To answer your question though
Wherever your java file is is where it's going to think "home is" make yourself a java workspace to put your java source files in and inside it create a folder to put any assets you want in that way you will simply be able to call "apple.jpg"
if you want use the file name only, the file path ("apple.png")is relative to the source folder. so you have to place it in there.
you could also use absolute the file path to your desktop (sthg like "C:\Users\your.name\Desktop")
From the javadoc:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:
new ImageIcon("images/myImage.gif")
As #Shriram mentioned, when you only specify the filename (with extension), it will search for that file in the current directory.
Hint: There exists an constructor overload which takes an URL as argument.

where do i put images for icons in java (netbeans) and how do i link them to the code?

I'm trying to make a Jframe class that has buttons with icons
public ImageIcon Flag = new ImageIcon(getClass().getResource("resources/Flag.png"));
Gives me a null pointer exception
"C:\Users\Khalidi\Documents\NetBeansProjects\MineSweeper\resources\Flag.png"
Is the full directory to reach the image I want
I created the folder resources to house the images I need
Where should i place the images? And what line of code should i be writing?
Thanks in advance
Try using the package path with the same method.
for example, if my image is in org.nisheeth.resources package, it should be written as follows.
public ImageIcon flag = new ImageIcon(Test.class.getResource("/org/nisheeth/resource/Flag.png"));
When you're loading your images using getClass().getResource(), the JVM in fact uses your CLASSPATH to load the resource (you should take a close look at Class#getResource(...)).
As a consequence, to have your resource available, you must push it to your project output folder (must be something like target, no ?).
As you asked for conventions: using the Maven build infrastructure, you would have
src/main/java - java packages
src/main/resources - resources like your images
src/main/resources/images/Flag.png - some resource (no convention)
In your created jar / .classes
/images/Flag.png
public ImageIcon Flag = new ImageIcon(getClass().getResource("/images/Flag.png"));
Here, Class.getResource() uses a relative path to the package of the class; therefore, using an absolute path as above ("/...") is easiest.
You can simply place a folder resources to the folder with compiled classes and make ImageIcon like this.
public ImageIcon Flag = new ImageIcon("resources/Flag.png");
Create a package say ImgPack and paste all your images to this package and access all the images using
ImageIcon ii = new ImageIcon(System.getProperty("user.dir")+"\\src\\ImgPack\\<Imagename.extention>");

How to get the path to the java file with the main method (src dir) [duplicate]

I need to get a resource image file in a java project. What I'm doing is:
URL url = TestGameTable.class.getClass().
getClassLoader().getResource("unibo.lsb.res/dice.jpg");
The directory structure is the following:
unibo/
lsb/
res/
dice.jpg
test/
..../ /* other packages */
The fact is that I always get as the file doesn't exist. I have tried many different paths, but I couldn't solve the issue.
Any hint?
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
leading slash to denote the root of the classpath
slashes instead of dots in the path
you can call getResource() directly on the class.
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
if you are calling from static method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

Issue with JavaLoader while loading jsoup

I am trying to load jsoup using JavaLoader but I am getting an initiation error:
<cfscript>
// An Array with absolute file paths of the referred jar files.
paths = expandPath("jars/jsoup-1.7.3.jar");
//Creating a java loader object by passing in the array containing the file paths -
loaderObj =createObject("component","javaloader.JavaLoader").init([expandPath('jars/jsoup-1.7.3.jar')]);
//So now, we can simply create a instance of an object from the 'bmw' and 'pulsar' class.
writedump(loaderObj);
abort;
jsoup = loaderObj.create("org.jsoup.Jsoup");
</cfscript>
Object Instantiation Exception.
Class not found: org.jsoup.Jsoup
The error "Class not found" means that Javaloader could not find the requested class.
This suggests that expandPath('jars/jsoup-1.7.3.jar') is not resolving to the correct location for that file.
To see where it is looking, just dump it out:
writeDump( expandPath('jars/jsoup-1.7.3.jar') );
That will tell you where JavaLoader is being told to look, so you can then either move the existing jsoup jar file to that location, or update the path to point to where the jar file currently is.
Depending on your application, you may find it useful to setup /jars as a mapping, so you can refer to /jars/jsoup-1.7.3.jar and know that the mapping will be used to resolve the path.

Get a resource using getResource()

I need to get a resource image file in a java project. What I'm doing is:
URL url = TestGameTable.class.getClass().
getClassLoader().getResource("unibo.lsb.res/dice.jpg");
The directory structure is the following:
unibo/
lsb/
res/
dice.jpg
test/
..../ /* other packages */
The fact is that I always get as the file doesn't exist. I have tried many different paths, but I couldn't solve the issue.
Any hint?
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
leading slash to denote the root of the classpath
slashes instead of dots in the path
you can call getResource() directly on the class.
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
if you are calling from static method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

Categories