Search code examples
javaimageresourcesimageicon

Java - How to add an image to resource


I really have a problem adding images to my java project, and before you ask, yes i have searched already and tried everything, but i just can't get it working.

Here is my problem:

At the moment i am using this code to get the images:

        ImageIcon goldIcon = new ImageIcon("res/Gold_coin.png");
        ImageIcon silverIcon = new ImageIcon("res/Silver_icon.png");
        ImageIcon copperIcon = new ImageIcon("res/Copper_icon.png");

My project structure is as following:

I have one project folder with two sub folders.

Both sub folders are specified as source folders, one is the "src" folder and the other one i named "res". In the "src" folder i have one package with all classes in it. In the "res" folder i have all the images saved.

Now the strange thing is, the "Gold_icon" DOES work, but both silver and copper do NOT. I am using eclipse luna and if someone could give me a step by step instruction how to add an image would be really nice.

Because all i find is always "add to resource" , "add it to resources folder" and honestly, i tried creatig a new folder, i copied it to the "src" folder, i tried every possible call, from ("res/Gold_coin.png") over ("/Gold_coin.png") to ("Gold_coin.png") and ("/res/Gold_coin.png")

I refreshed the project, the folders, the package, the classes, i restarted eclipse but nothing helps

I just don't get it..

Please help :(

If you need the information what i want to do with this images afterwards, i am adding them together into a JPanel with flowlayout which i write into a JTable cell with a cellrenderer, which is everything working with the gold icon, but not the other two. And it also does not work to remove the gold icon (because i thought maybe for whatever reason only the first icon works..) but then nothing is displayed

Folder structure and adding imageicons

Adding imageicons to JPanel

Output


Solution

  • You should use getResource to load images or whatever from resource folder.

    For example:

    String pathToImage = "res/Gold_coin.png";
    ImageIcon myIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImage));
    

    or with all project path: nameOfProject/res/Gold_coin.png.