1

I am creating a simple GUI using swing in Java and simply want to display a JPEG image as a banner in the frame. I have the image working properly, but the filepath is subject to change as this will be sent to other people. The image is stored in the folder I will be sending to others. I am looking for a way to ensure that no matter what location the the folder has been moved to, the image will display. I am new to this site, and fairly new to Java. Thanks for you help in advance.

Relevant Code:

ImageIcon numberImage = new ImageIcon("C:\\Users\\Me\\Desktop\\numberGame\\numbers.jpg");
Image image = numberImage.getImage();
Image newimg = image.getScaledInstance(300,120,java.awt.Image.SCALE_SMOOTH);
numberImage = new ImageIcon(newimg);
JLabel imageLabel = new JLabel("", numberImage, JLabel.CENTER);
JPanel imagePanel = new JPanel(new BorderLayout());

imagePanel.add(imageLabel, BorderLayout.CENTER );
Keiwan
  • 8,031
  • 5
  • 36
  • 49
Justiciar
  • 356
  • 1
  • 3
  • 20
  • Put the image into your classpath, then it's going to be always available via a `"classpath:/package/name/file.jpg"` path. You may want to look into maven for building your project. – Tassos Bassoukos Apr 25 '16 at 21:26
  • 1
    Possible duplicate of [Java Swing: Displaying images from within a Jar](http://stackoverflow.com/questions/31127/java-swing-displaying-images-from-within-a-jar) – nhouser9 Apr 25 '16 at 21:33
  • @nhouser9 but if the program is not inside a Jar, specifying a relative path should just work for this problem. I think if it's not a Jar the solution is pretty much simple. – piraces Apr 25 '16 at 21:50

2 Answers2

1

To ensure, the image could be displayed in every context, you must specify a relative path instead of an absolute path.

You could change:

ImageIcon numberImage = new ImageIcon("C:\Users\Me\Desktop\numberGame\numbers.jpg"); 

To:

ImageIcon numberImage = new ImageIcon("numbers.jpg"); 

And this should work in other contexts (with other different paths). Or if the image is in a directory inside your program put "\imageFolder\numbers.jpg".

This should work, the main change is to replace the absolute path with a relative path.

piraces
  • 1,320
  • 2
  • 18
  • 42
0

You want to use a relative path instead of absolute. Here's a quick explanation that's pretty clear.

http://www.xyzws.com/javafaq/what-is-the-difference-between-absolute-relative-and-canonical-path-of-file-or-directory/60

Good luck. :)

Robert Saba
  • 31
  • 1
  • 7