Java applet in application
I've written a Snake clone in the process of learning how to program in Java. It is an applet that uses images (loaded in the init() method using getImage(getDocumentBase(), "gfx/image.png");
When I run the applet in my IDE (Eclipse) it runs fine and all the images are shown.
My goal however is to create an executable jar file that I can pass around easier than an applet. So I created a new class and used a JPanel to host my applet. Now the problem is that getDocumentBase() always returns null, resulting in the images not being found on the filesystem, resulting in an empty screen.
I know the game开发者_JS百科 runs cause I can navigate all the menus and see all the text that is printed. It's just the images that aren't loaded.
Is there any way around this? Should I load my images another way?
Thanks
You can load resources from within you jar-file by using the getResource()
method from Class
. On DevX there's a nice tutorial showing you how to do that for applets and applications:
http://www.devx.com/tips/Tip/5697
There is also an article from Oracle describing how to access resources in a location-independent manner:
http://download.oracle.com/javase/1.4.2/docs/guide/resources/resources.html
Basically you're accessing an image like this:
URL myurl = this.getClass().getResource("/myimage.gif");
Toolkit tk = this.getToolkit();
img = tk.getImage(myurl);
Load your image like this instead:
public void init() {
URL url = getClass().getResource("/gfx/image.png");
Image image = getImage(url);
}
Then add your gfx/image.png
file to your jar and keep the path. Note that jar files are just zip files.
精彩评论