简体   繁体   中英

How to access a Image file in a Eclipse Project Folder

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?

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

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.

I am doing that the same way

 String filename = "logo.jpg";

 Main.getClass().getClassLoader().getResource(filename);

And the file structure looks like this

/src/main/java/com/hauke/Main.java

/resource/logo.jpg

My problem was before that I named the direcotry "resources" and it should be "resource"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM