How do I properly reference images in Java?

  • Context: Java 
  • Thread starter Thread starter BiGyElLoWhAt
  • Start date Start date
  • Tags Tags
    Image Java
Click For Summary

Discussion Overview

The discussion revolves around the proper referencing of image files in a Java application, specifically in the context of loading images into an array for a tic-tac-toe game. Participants explore issues related to syntax, relative paths, and the use of class loaders.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Exploratory

Main Points Raised

  • One participant shares a code snippet that results in a null pointer error, suggesting potential issues with syntax or relative referencing.
  • Another participant questions the use of the getClass() method in the context of the ImageIcon constructor, suggesting that it may require an object reference.
  • A different participant proposes that the getResource() method is being used incorrectly and suggests using getImage() to retrieve the image after obtaining the URL.
  • One participant emphasizes the importance of verifying the existence of the "img" directory in the working directory to ensure the path is correct.
  • Another participant mentions the need to retrieve the class loader when accessing resources, particularly if the images are packaged within a JAR file.
  • One participant notes that their src folder only contains .java files, indicating a potential issue with the project structure.
  • A later reply explains the build process in Java, highlighting where resources should be stored to ensure they are included in the final JAR file.

Areas of Agreement / Disagreement

Participants express varying opinions on the correct method for referencing images, with some suggesting different approaches and others questioning the existing code. There is no consensus on a single correct method, and multiple competing views remain.

Contextual Notes

Participants mention the need for a proper directory structure and the implications of resource packaging in JAR files, but there are unresolved questions about the specific setup required for the project.

BiGyElLoWhAt
Gold Member
Messages
1,637
Reaction score
138
Here's the snippet I'm erroring on. I'm sure I have a bad syntax or I'm not relative referencing correctly or something. Null pointer.
Java:
        xo = new ImageIcon[2][2];
        xo[0][0] = new ImageIcon(getClass().getResource("img/x1.png"));
        xo[0][1] = new ImageIcon(getClass().getResource("img/o1.png"));
        xo[1][0] = new ImageIcon(getClass().getResource("img/x2.png"));
        xo[1][1] = new ImageIcon(getClass().getResource("img/o2.png"));
        player = 0;
        style = 0;
        setOpaque(true);

Basically I just want to load in my images to an array to be referenced later. It's for a tic tac toe game. 2 players, 2 styles of x's and o's.
I have:
workspace -> project 2 -> img -> (png files)

I pretty much ripped this off stack exchange, and that is how the user was referencing their images, except with 2 slashes. I tried changing that. It didn't do anything. Same error. Am I referencing improperly? Or am I doing something wrong in the ImageIcon?

*edit
http://stackoverflow.com/questions/17110315/jbutton-background-image
this is where I got the code from
 
Last edited by a moderator:
Technology news on Phys.org
One problem with code like this is that if something goes wrong, it's hard to tell exactly where things are going wrong.
Java:
 xo[0][0] = new ImageIcon(getClass().getResource("img/x1.png"));

I haven't done any coding in Java for about 20 years, so I'm not very familiar with all of the APIs that make up the language these days. In the ImageIcon() constructor, you're calling getClass(). Is this a static method? If not, you need an object on which to call it.

Here's some other code I found:
Java:
Image img;

public ResourceTest() throws Exception {
   URL myurl = this.getClass().getResource("/myimage.gif");
   Toolkit tk = this.getToolkit();
   img = tk.getImage(myurl);
}
Comparing this snippet to your code, it appears that you are using getResource() incorrectly. This method apparently returns the URL for a resource, which in your case would be the URL for an image, not the image itself. Take a look at the code I copied. He or she used getResource to return a URL, and then used getImage() to actually get the image.

As far as the forward slashes in the code you referenced on SE, I can't think of any reason why someone would use two forward slashes. Two backslashes, yes, but not two forward slashes. Many times when a program fails to load a file, it's because a relative path to the file can't be accessed from the location where the code is. In your working directory, is the a directory named img?

When I was doing Java, there wasn't much in the way of debugging capabilities. By now, I'm fairly sure they are pretty full featured. I would think you should be able to pause your program and do a quick watch to evaluate some expression (like your code to get a resource. That would tell you exactly what is failing.
 
Last edited by a moderator:
  • Like
Likes   Reactions: QuantumQuest and jedishrfu
I think there's a step missing here:

https://docs.oracle.com/javase/tutorial/deployment/webstart/retrievingResources.html

Notice in retrieving resources you need to retrieve the classloader first. That's if the images are in your jar file as is common if you use maven to build your project and your images are stashed in ./src/main/resources/images
subdirectory.

So try this instead:

Java:
        ClassLoader classLoader = this.getClass().getClassLoader();
        xo = new ImageIcon[2][2];
        xo[0][0] = new ImageIcon(classLoader.getResource("img/x1.png"));
        xo[0][1] = new ImageIcon(classLoader.getResource("img/o1.png"));
        xo[1][0] = new ImageIcon(classLoader.getResource("img/x2.png"));
        xo[1][1] = new ImageIcon(classLoader.getResource("img/o2.png"));
        player = 0;
        style = 0;
        setOpaque(true);
 
Mark44 said:
In your working directory, is the a directory named img?
Yes there is. The directory setup is Eclipse Workspace -> Project Folder [titled project 2] -> img [houses the images
jedishrfu said:
I think there's a step missing here:

https://docs.oracle.com/javase/tutorial/deployment/webstart/retrievingResources.html

Notice in retrieving resources you need to retrieve the classloader first. That's if the images are in your jar file as is common if you use maven to build your project and your images are stashed in ./src/main/resources/images
subdirectory.

So try this instead:

Java:
        ClassLoader classLoader = this.getClass().getClassLoader();
        xo = new ImageIcon[2][2];
        xo[0][0] = new ImageIcon(classLoader.getResource("img/x1.png"));
        xo[0][1] = new ImageIcon(classLoader.getResource("img/o1.png"));
        xo[1][0] = new ImageIcon(classLoader.getResource("img/x2.png"));
        xo[1][1] = new ImageIcon(classLoader.getResource("img/o2.png"));
        player = 0;
        style = 0;
        setOpaque(true);

In this case, I would want to actually change my directory setup, though, correct?
 
I just went to try it, however, I don't have anything in my src folder other than my .java files.
 
What happens during build is classes are compiled and placed in a target directory (called "target" for maven, "build" for ant I think) and resources are copied over to it as well. Then the whole collection is zipped up into a jar file along with a META-INF/manifest.mf file.

Here's where your stuff should be stored to be placed in the jar file by build.

http://ant.apache.org/easyant/history/trunk/ref/Directorystructure.html

img should be moved to src/main/resources/img
 
  • Like
Likes   Reactions: BiGyElLoWhAt

Similar threads

  • · Replies 14 ·
Replies
14
Views
6K
  • · Replies 6 ·
Replies
6
Views
7K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 15 ·
Replies
15
Views
3K
  • · Replies 23 ·
Replies
23
Views
8K
  • · Replies 6 ·
Replies
6
Views
3K
Replies
1
Views
2K