Search code examples
javaeclipseembedded-resourceimageicon

Accessing image paths in Eclipse


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!


Solution

  • 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;
    }