Matan Cohen
Matan Cohen

Reputation: 1

Location of image in exported project folder

In my current code I write the specific location of the images I want to use in my project, now, these locations are only correct until I move the image to a different directory or open the application in a different computer.

Where do I place the images (where to place them in the exported folder) I want to use in my project?

The exported project is a zip file, once extracted, I have 2 folders within the extracted folder, one named nbproject other is src, one text file named build another .mf file called manifest inside nbproject I have two text files and two .properties files inside src I have my four classes.

Where do I put the images I want to use in the project? And once I place them, what directory do I write in my project?

Here's an example of how I use an image:

// Main menu background image

bgg[0] = new ImageIcon("D:/NetBeans/NetBeans projects/Java/Project Images/bg option for Vanguard.jpg").getImage();

And then I draw the image all over the screen

My exported folder contents:

https://i.sstatic.net/ti2NE.png https://i.sstatic.net/RAMjO.png

EDIT: Thought it worked but it keeps giving an exception on other people's computers, perhaps this isn't the reason beause I moved the images around in my PC and it worked but still.

Upvotes: 0

Views: 587

Answers (3)

Malik Brahimi
Malik Brahimi

Reputation: 16711

Don't use a strict path, use a relative path like so:

Main.java

String path = "Project Images/bg option for Vanguard.jpg";
bgg[0] = new ImageIcon(getClass().getResource(path)).getImage();

In order for this to be loaded, you must place a folder called Project Images in the directory in which your Java files are. Then place the image bg option for Vanguard.jpg in this folder. Be sure to compile the program in you IDE so it can make a copy for the compiled version.

Upvotes: 0

Dima Maligin
Dima Maligin

Reputation: 1482

The path where your program looks for resources can depend on how you run the program. If you ran it via console/terminal the initial path starts at the path of the *.class file you ran. If you run it from an IDE this path may change, in Eclipse the path starts at the Project dir and not the src folder. You can find out the exact path by calling System.getProperty("user.dir") that will return the current working path as a String.

Upvotes: 0

Jefry Sastre
Jefry Sastre

Reputation: 126

Since you are writing the directory in your code.

bgg[0] = new ImageIcon("D:/NetBeans/NetBeans projects/Java/Project Images/bg option for Vanguard.jpg").getImage();

When you run the project in another computer or move the image to another location, the program can't find the path to the picture, so there is an error. Instead of using the full path. Copy the images to your project folder and use relative paths.For instance : "images/Vanguard.jpg".

Upvotes: 1

Related Questions