Accessing image paths in Eclipse

23,841

Solution 1

You should have a resource folder with the folder named Images in that, then it should work.

Example:

enter image description here

How I access those icons:

public BufferedImage icon32 = loadBufferedImage("/icon/icon32.png");
public BufferedImage icon64 = loadBufferedImage("/icon/icon64.png");

private BufferedImage loadBufferedImage(String string)
{
    try
    {
        BufferedImage bi = ImageIO.read(this.getClass().getResource(string));
        return bi;
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}

Solution 2

Try importing the images to the path were your ".java" source file is located. Try below in eclipse: right click on your ".java" file, select Import->File System->From Directory(provide the path where images are located)->Select the images and click Finish.

You can see the images getting listed in the path where ".java" source is located. You can directly use the image file name in you code. Thanks, P

Share:
23,841
Jared Nielsen
Author by

Jared Nielsen

Updated on January 07, 2020

Comments

  • Jared Nielsen
    Jared Nielsen over 4 years

    I'm trying to access some images in my Java code. The code to call the images is below.

    public final ImageIcon whitePiece = new ImageIcon(getClass().getResource("Images/whitecircle.PNG"));
    public final ImageIcon blackPiece = new ImageIcon(getClass().getResource("Images/blackcircle.png"));
    public final ImageIcon tiePiece = new ImageIcon(getClass().getResource("Images/tiecircle.PNG"));
    public final ImageIcon boardPic = new ImageIcon(getClass().getResource("Images/gameboard.PNG"));
    

    However, this returns the following error:

    Exception in thread "main" java.lang.NullPointerException
        at javax.swing.ImageIcon.<init>(Unknown Source)
        at jared.othello.GameInterface.<init>(GameInterface.java:26)
        at jared.othello.Main.main(Main.java:22)
    

    Line 26 is the first line of the above code. I am almost positive that something is wrong with my file directory naming, but I can't figure out what's wrong or how to fix it. I've created a source file named 'Images' within my project and placed the images in the folder, like so:

    Project Configuration

    What am I doing wrong, and what is the correct filename syntax? Thanks!

  • Jared Nielsen
    Jared Nielsen about 11 years
    I tried that (see my edit), and it didn't seem to work. Any ideas why?
  • syb0rg
    syb0rg about 11 years
    Your file tree should look extremely similar to the one in my answer then, and each folder icon should be identical. Also, you should have the leading / when accessing them.
  • syb0rg
    syb0rg about 11 years
    Yes, without them I get an IllegalArgumentException. With them they work perfectly.