Subscribe to Dogstopper's Code Mania        RSS Feed

Loading Images for Gaming

Icon Leave Comment
This will be a relatively short blog entry. On many occasions, I have been asked how to load an image in Java that can be easily used for gaming purposes. Well, the answer? Many ways. The way I will show you in this entry is not the usually suggested method, but personally I have found it much easier to use than other classes like ImageIcon. The advantage of my method is that it utilizes the powerful Image class directly. Let's take a look.

JPanel jp = new JPanel // Some JPanel, whether it be new or not.

public Image loadImage(String imageName) {
	Image image = null;
	if (jp != null) {
		// Locate and load the image
		URL fileLocation=getClass().getResource(imageName);
	image = Toolkit.getDefaultToolkit().getImage(fileLocation); 

		 // Now prepare it to be used
	jp.prepareImage(image, null);
	return image;	

The downfall of this code is that it requires the use of a JPanel, JFrame, or ANY Component for that matter in order to prepare this Image for painting. Otherwise, it takes 1 paint cycle for it to actually paint. This method is good for things such as engine which moderate gameplay. In this example, I have the images located in the same Jar file in a subdirectory called images.

Here is the simple structure:
- src 
   -- My Java files go here
   - images
	   -- Images go here

Hope that clears some things up!

0 Comments On This Entry


January 2021

101112131415 16

Recent Entries

Search My Blog

Recent Comments

1 user(s) viewing

1 Guests
0 member(s)
0 anonymous member(s)