How to access a Image file in a Eclipse Project Folder

30,695

Solution 1

You need to place your resources in a java source directory for them to be visible. You have two options:

  1. Move your "resources" folder under your existing "src" folder.

  2. Create a new source folder just for resources. You can do that in Java Build Path page of project properties.

Several things to watch out for...

  1. Pay attention to your capitalization. Java resource lookup is case sensitive.

  2. The path that you would use will be relative to the source folder (not project root). For instance, if you make your resources folder a source folder, your path will need to be "images/...". If you want to preserve resources folder in the lookup path, you will need to create an extra folder level in your project to serve as the source root for resources.

  3. I am not certain whether it is an actual problem, but resources paths should not start with a leading slash. They aren't really paths in a traditional sense. Think of them as package-qualified class names, but with '/' instead of '.' as the separator.

Solution 2

U can use this way I have following package structure

  • src/test (package test contain Java files)

  • src/images (folder images contain images)

I am going to get image from src/images/login.png at src/test/*.java

JLabel label = new JLabel(new ImageIcon(getClass().getResource("/images/login.png")));

Share:
30,695
StephenHynes
Author by

StephenHynes

Updated on April 05, 2020

Comments

  • StephenHynes
    StephenHynes about 4 years

    I have a single image file in a folder in my Eclipse project that stores a image file (logo.jpg). However I don't know how to access it in my main program.

    I had tried the following

    private static URL logoPath
    
    public class MainApplication
    {
         public void createGui()
         {
              logoPath.getClass().getResource("/Resources/images/logo.jpg");
              ////
         }
         /////
    }
    

    Problem is I keep getting a null pointer exception so obviously that path is done wrong or else the logoPath.getClass() is tripping it up.

    Any ideas?