0

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 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

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.