3

I am currently developing a game, and have encountered a very burdensome problem.

I want to draw a picture on the screen but every time I try to read the resource / picture I get NULL. I tried 2 kinds of methods to read the picture but still couldn't.

But when I moved the image into the package that contains the class from which I was trying to read the image the image appeared.

So the problem is that i just can't access resources outside of the current package. And i need to know how can i do that, how can i access this resource. It has to be a resource that I can use even after exporting the game to a JAR file.

My Project Structure

Code I tried (The first one is buffered image and the second is just image type:

    try {
        image = ImageIO.read(getClass().getResource("blocks.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    --------------------------------------------------------------

    image = new ImageIcon(getClass().getResource("blocks.png))).getImage();

I hope the question is clear enough.

RDev
  • 41
  • 6
  • 1
    Does this answer your question? [Loading resources using getClass().getResource()](https://stackoverflow.com/questions/2343187/loading-resources-using-getclass-getresource) – Arvind Kumar Avinash Jun 13 '20 at 21:26
  • @ArvindKumarAvinash I couldn't find the solution to this question. I tried some of the answers but it still doesn't work for me. – RDev Jun 13 '20 at 21:35
  • What about `/package/path/to/the/resource.ext` mentioned in the accepted answer? Did you try this? Did you check the [documentation](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Class.html#getResource(java.lang.String))? – Arvind Kumar Avinash Jun 13 '20 at 21:37
  • @ArvindKumarAvinash Yep. Didn't work for me. – RDev Jun 13 '20 at 21:39
  • That's because I need to access the resources folder. But this code snippet only allows me to access resources in other packages and not a folder. @ArvindKumarAvinash – RDev Jun 13 '20 at 21:45
  • 1
    If you read the [documentation](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#getResource%28java.lang.String%29) carefully, you’ll see that your code is looking for blocks.png *in the same package* as your class. To load a blocks.png which is not in any package, but rather is in the root of the resource tree, add a slash: `getClass().getResource("/blocks.png")` – VGR Jun 14 '20 at 03:34

1 Answers1

3

Try creating a package called "resources", instead of a folder, and then access your image as "resources/blocks.png".

Dan M
  • 4,340
  • 8
  • 20