Justiciar
Justiciar

Reputation: 376

java - Reading a image filepath that may change

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 );

Upvotes: 1

Views: 517

Answers (2)

piraces
piraces

Reputation: 1348

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.

Upvotes: 1

Robert Saba
Robert Saba

Reputation: 31

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. :)

Upvotes: 0

Related Questions