javaimagepathbufferedimage

VSCode getResource cannot find the resource


I am trying to load a Sprite file in to a game from a tutorial.

The tutorial is built in Eclipse and the person uses the IDE settings to add a resource folder allowing him to use getResource().

I am using VSCode, VSCode misses the .classpath path file in which the setting seems to of been placed. VSCode doesn't have a settings option for setting a Java Resource Directory.

I wish to be able to use getResource("directory/file.png")

I have tried adding a .classpath file and inputting the resources directory and results were the same.

I have tried loading it in different ways nothing is working.

package n0ngames.SandboxRPG.graphics;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SpriteSheet {
    private String path = null;
    public final int SIZE;

    public int[] pixels = null;

    public static SpriteSheet tiles = null;

    public SpriteSheet(String _path, int size) {
        this.path = _path;
        this.SIZE = size;
        this.pixels = new int[size * size];

        load();

        tiles = new SpriteSheet("C:/dev/SandboxRPG/res/textures/spritesheet.png", 256);
    }

    private void load() {
        try {
            BufferedImage image = ImageIO.read(SpriteSheet.class.getResource(path));
            int w = image.getWidth();
            int h = image.getHeight();

            image.getRGB(0, 0, w, h, pixels, 0, w);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The offending line is this one BufferedImage image = ImageIO.read(SpriteSheet.class.getResource(path)); the getResource(path) isn't working.

I would assume there is a way to get this line working as if VSCode couldn't it would be a large language feature missing form the Java language while using VSCode, so there must be a way.

Can anyone explain how to get this line to work correctly?


Solution

  • The solution was to set the project up correctly.

    Step 1: Press Ctrl + Shift + P

    Step 2: Type Java

    Step 3: Select Java: Create Java Project

    Step 4: Name project

    This will build a standard blank Java project for use.