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.
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:
Hope that clears some things up!
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 →
S | M | T | W | T | F | S |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Recent Entries
Search My Blog
Recent Comments
My Blog Links
1 user(s) viewing
1 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)