We are building a game that uses some sprites (images) which are simple GIF files. We used to have those files in a separate folder called 'sprites' and loaded them like this:
This worked fine, but it requires the same folder of sprites after distributing, leaving the sprites 'vulnerable' to editing or even removing by the user. We don't want that.
ImageIcon icon = new ImageIcon("sprites/image1.gif");
So, I decided to place all the sprites into the same folder as the java source files. If I understand correctly, they should then automatically be 'embedded' into the JAR file, right?
Then, to load an image, I use the following code:
Here, 'MainMenu' is the main class, I'm not sure if I have to use this in ALL classes (as the code is also present in other classes).
URL url = MainMenu.class.getResource("image1.gif");
Image img = Toolkit.getDefaultToolkit().getImage(url);
Anyway, this seems to work just fine when debugging or running from within the IDE (NetBeans). As soon as we compile and try to run the JAR executable however, it fails.
The game starts up fine, shows a few of the images, but not all of them. As far as I can see, our method of loading a level fails somehow. But I changed NOTHING in that method at all. The only thing I changed is how to sprites are drawn (I showed how above), and I'm sure that is where the problem lies.
I use the code as above in the drawing method to draw sprites on to the level, but I use it in other methods as well, to draw a logo onto a panel.
As said, from the IDE, everything works. But when running the compiled JAR file, only some things work. The logo works, but the sprites don't. And I'm using the same drawing method....
Does anyone have any idea what could cause this, especially why it works from within the IDE but not from outside?