Hello! i’m still learning the ways of Java and eclipse, i’ve started creating a space invaders clone(gotta start somewhere right?) But the game isn’t really where my problem is. I’ve spent the last few days trying to export to a jar file. And i finally managed it but then i hit a wall with my code within the jar trying to find the pictures.
Which is really where i’m still kind of confused. I found a site http://ubuntuforums.org/showthread.php?t=711238 that helped me out and now the code works but i don’t know why it works and that’s bothering me more then anything.
i’ve imported the images into eclipse to help automate the export into a jar file. I was able to manually copy the pictures into the jar and it worked before but i’d rather eclipse just handled it for me.
Anyway in the jar the files are under a folder called /Images/ and here’s the code i was using:
private Image image;
private String craft = "./Images/cannon.png";
ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
image = ii.getImage();
courtesy of: http://zetcode.com/tutorials/javagamestutorial/
Now i’m using
java.net.URL imgURL = getClass().getResource("/Images/cannon.png");
image = Toolkit.getDefaultToolkit().getImage(imgURL);
Now the code automagically works but i’m not sure why. I was wondering if someone could explain the differences between these two? Do i have to use the second one? is it more efficient? the path to the images looks like it was exactly the same so i’m not sure why the other one didn’t work. I noticed i needed to import java.awt.Toolkit for this one for obvious reasons. But i’m not sure what’s up with java.net.URL
Anyway i’d apreciate a point in the right direction. There’s so much code out there and so many ways to do things that i’m not all that sure whether i’m heading in the right direction or not. This could be a horribly inefficient way of doing it for all i know.