0
\$\begingroup\$

I am using Netbeans to create my game. The images do seem to load when I run it in Netbeans. However, the built jar file only leaves me with a blank screen.

This is how I call the images in my game.

public Image playerSprite = playerSprite = Toolkit.getDefaultToolkit().getImage("sprites\\spritesL.png");

I put all image resources in a folder called sprites, and I declared it as a Source in the Project Properties. In addition, the image files does appear in the root directory of the JAR file, but cannot seem to access it.

enter image description here

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Java can be quite a pain when trying to load files that are inside the .jar. So first, try to put your sprites folder outside of your jar, on the same level. See if that works.

To load files that are inside the jar, you must use this following piece of code to retreive it's URL:

getClass().getResource("myimage.png")

So your line of code would be :

public Image playerSprite = playerSprite = 
   Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("sprites\\spritesL.png"));

NOTE: You might need to call .toString() on the return value of .getResource() since it returns a URL object and .getImage() takes a String as parameter.

See if that works too. If there's any problems, feel free to ask.

\$\endgroup\$
3
  • \$\begingroup\$ Thanks for the response! However, replacing the code didn't work and instead left an error on the console. \$\endgroup\$
    – LaPXL8R
    Commented Jun 11, 2015 at 18:35
  • \$\begingroup\$ @LaPXL8R This is a NullPointerException. Test your code to see where it comes from (probably from the .getResource() function). \$\endgroup\$ Commented Jun 11, 2015 at 18:38
  • \$\begingroup\$ @LaPXL8R I cannot download your file and I won't, because this site is not a "debug my code" site. Please remove the link from your comment and ask a new question if another problem arises. \$\endgroup\$ Commented Jun 11, 2015 at 18:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .