0

I am sure this has a simple fix but I'm having a hard time finding a solution.

I normally use my Macbook pro, but I am trying to make sure that a project I'm working on is functioning in Windows 7 as well. I'm running bootcamp on my Macbook pro right now.

My only issue is importing images.

Using Eclipse on my Mac, I can just import the images into my project folder, look at their properties, and C+P the direct path into my import statement. However, this method is not working when I switch over to Windows 7. Since Windows 7 uses back slashes, I tried putting the entire path using \ to replace each single \ in the path. This does not work. I've also tried simply doing "\Project\image.png" but that also does not work. With single or double back slashes.

Here is my code for importing my file:

picLabel.setIcon(new ImageIcon("C:\\Users\\Kaitlyn\\Documents\\JAVA\\Project\\Project1\\src\\Project\\icon.png"));

I have yet to understand why it's not importing the images. The code has not been modified, except for the paths, from the code I used on Mac OS X. Is there something I am doing incorrectly when trying to import images using Windows 7?

Thank you!

Kaitlyn
  • 129
  • 1
  • 2
  • 11
  • Don't use absolute paths, use relative paths instead, or embed the images within the jar itself and use Class#getResource instread – MadProgrammer Dec 07 '14 at 20:57
  • Yeah, relative paths should be best! I just wanted to get it working at all first! XD Thank you!:) I don't know what a Jar is, I'll have to do more research. In the meantime, using relative paths, I believe I have to use forward slashes rather than back slashes?? – Kaitlyn Dec 07 '14 at 21:15
  • 1
    Yes, you can pretty much use `/` all the time, under Windows, the JVM will correct for them automagically – MadProgrammer Dec 07 '14 at 21:16

1 Answers1

1

You should just be able to do something like the following:

picLabel.setIcon(new ImageIcon("/Project/icon.png"));

Using the file path like in this example is a better way to retrieve files in any program. This makes it more compatible. So if you were going to deploy this program to other servers/machines you would be looking for the file in your project and not on the machine.

Here are some other questions and docs that might help. https://docs.oracle.com/javase/tutorial/uiswing/components/icon.html

How to add an ImageIcon to a JFrame?

Java Swing ImageIcon, where to put images?

Community
  • 1
  • 1
Trevor
  • 67
  • 5
  • Thank you! I was wondering if it is appropriate to use the forward slashes? In windows, the paths all contain backslashes. I believe I tried the shorter path already as you mentioned, but maybe I included the double back slashes instead of single forward slashes. – Kaitlyn Dec 07 '14 at 21:02