Justiciar Justiciar - 5 months ago 7x
Java Question

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


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


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.