Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (541)
Games in Android Showcase (133)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  [SOLVED] Loading .gif images - url = null trouble  (Read 576 times)
0 Members and 1 Guest are viewing this topic.
Offline evil_error

Junior Newbie





« Posted 2013-09-24 18:31:18 »

Hello all!

Quote
Oh...
Another quick question:

Am I referencing the images correctly? Am I supposed to start the reference as if I'm in the src ("sprites/alien.gif") folder or somewhere else (in which case, where)?
I can't reference any of the gifs (getting the fail msg I've implemented) Sad


ref = "sprites/homer.gif"

but when it gets to assigning URL, url = null
-_-

I am thoroughly annoyed with my current problem. I'm attempting to load an image and display it on screen (simple, huh?), but I can't figure out what I'm doing wrong. To explain the code real quick - Screen class creates a JFrame and initiates everything. Sprite class is a wrapper for Image, contains a reference to an Image, a constructor and a draw method. SpriteStore is a singleton class for managing Sprite - mainly, I don't want to load the same Sprite (Image) more than once. Thus - each unique sprite is stored in a HashMap (hashing is done according to the reference), upon requesting a Sprite, the HashMap is checked first. If the Sprite is already is the HashMap, I return the Sprite, otherwise, I load the sprite via the reference, store it in the HashMap and return it. Pretty simple and well understood.

Then, I decide to test it out, and load a random (.gif) image and draw it anywhere on the JFrame. The code breaks at:
1  
Sprite testSprite = spriteStore.getSprite("sprites/homer2.gif");


at the screen init. The error is:
1  
2  
3  
Exception in thread "main" java.lang.NullPointerException
   at Screen.<init>(Screen.java:17)
   at Screen.main(Screen.java:70)


I have no idea whats going on. The sprites/homer2.gif is located in my src folder. (I'm using Eclipse, if its relevant)



Here are three simple test classes:
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  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
import java.awt.Canvas;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.image.BufferStrategy;
import java.awt.Graphics2D;
import java.awt.Color;

public class Screen extends Canvas {
   private BufferStrategy strategy;
   private JFrame frame;
   private JPanel mainPanel;
   private boolean working;
   private SpriteStore spriteStore = SpriteStore.get();
   
   
   Sprite testSprite = spriteStore.getSprite("sprites/homer2.gif");  
   
   private Screen() {
      frame = new JFrame("Accelerated Graphics Testing");      
      mainPanel = (JPanel)frame.getContentPane();
      mainPanel.setPreferredSize(new Dimension(800,600));
      mainPanel.setLayout(null);
     
      this.setBounds(0, 0, 800, 600);
      mainPanel.add(this);
     
      frame.pack();
      frame.setResizable(false);
      frame.setVisible(true);
     
      this.createBufferStrategy(2);
      strategy = this.getBufferStrategy();
     
      //initEntity();
      working = true;
     
      runningLoop();
   }

   /*private void initiateTestSprite(String ref) {
      testSprite = spriteStore.getSprite(ref);
   }*/

   
   private void runningLoop() {
      long lastLoopTime = System.currentTimeMillis(), delta;
      //initiateTestSprite("sprites/alien.gif");
      while(working) {
         delta = System.currentTimeMillis() - lastLoopTime;
         lastLoopTime = System.currentTimeMillis();
         
         Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
         g.setColor(Color.CYAN);
         g.fillRect(0, 0, 800, 600);
         //
         testSprite.draw(g, 400, 200);
         //
         g.dispose();
         
         strategy.show();
         
         try {
            Thread.sleep(500);
         } catch(InterruptedException e) {}
         
      }
   }
   
   public static void main(String[] args) {
      new Screen();
   }
}




1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
import java.awt.Graphics;
import java.awt.Image;

public class Sprite {
   private Image image;
   
   public Sprite(Image image) {
      this.image = image;
   }
   
   public int getWidth() {
      return image.getWidth(null);
   }
   
   public int getHeight() {
      return image.getHeight(null);
   }
   
   public void draw(Graphics g, int x, int y) {
      g.drawImage(image, x, y, null);
   }
   
}



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  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
import java.util.HashMap;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.awt.GraphicsConfiguration;
import java.awt.Transparency;
import java.awt.Image;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SpriteStore {
   // singleton logic
   private static SpriteStore single;
   
   public static SpriteStore get() {
      return single;
   }
   
   //
   
   private HashMap sprites = new HashMap();
   
   public Sprite getSprite(String ref) {
      // if referenced .gif is loaded, return according sprite
      if(sprites.get(ref) != null)
         return (Sprite)sprites.get(ref);
     
      // otherwise, load the referenced sprite, insert it into the HashMap and return the newly inserted sprite
      BufferedImage sourceImage = null;
      try {
         URL url = this.getClass().getClassLoader().getResource(ref);
         if(url == null)
            fail("Can't find that :( " + ref);
         sourceImage = ImageIO.read(url);        
      } catch(IOException e) {
         fail("Failed to load :( " + ref);
      }
     
      // accelerated graphics memory allocation
      GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
      Image image = gc.createCompatibleImage(sourceImage.getWidth(), sourceImage.getHeight(), Transparency.BITMASK);
     
      image.getGraphics().drawImage(sourceImage,0,0,null);
     
      Sprite sprite = new Sprite(image);
      sprites.put(ref, sprite);
     
      return sprite;
   }
   
   private void fail(String msg) {
      System.err.println(msg);
      System.exit(0);
   }
   
   
   
}





In case it's relevant, I was following this tutorial.


Thanks in advance,
Regards Smiley
Offline Abuse

JGO Knight


Medals: 15


falling into the abyss of reality


« Reply #1 - Posted 2013-09-24 18:55:57 »

If you're using eclipse, you should learn to use the debugger to step through your code. It'll make finding the issue trivial.

From a quick scan of the code, it looks like...

private static SpriteStore single;

..... is never initialised.

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline evil_error

Junior Newbie





« Reply #2 - Posted 2013-09-24 19:36:29 »

What else is there to initialize in SpriteStore? There is only HashMap (initialized) and nothing else.
Upon requesting a sprite via reference, SpriteStore reacts by loading the image (not in store yet) or returning the existing one (referenced image is in store).


Also, upon stepping into the getSprite() method, the debugger says something like 'null thread...' and I can't investigate further... Sad
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Slyntax

Junior Devvie


Medals: 3



« Reply #3 - Posted 2013-09-24 19:58:42 »

What he's saying is that your variable 'single' is null. You never assign it to anything. Therefore when you call the get() method it returns exactly that... null

Change it to this...

1  
private static SpriteStore single = new SpriteStore();


or you can do something like...

1  
2  
3  
4  
5  
6  
7  
8  
9  
private static SpriteStore single;

// other code

public static SpriteStore get() {
      if (single == null)
          single = new SpriteStore();
      return single;
   }
Offline evil_error

Junior Newbie





« Reply #4 - Posted 2013-09-24 20:11:09 »

Of course it's something stupid like that...
Thanks guys. Good on you...


Oh...
Another quick question:

Am I referencing the images correctly? Am I supposed to start the reference as if I'm in the src ("sprites/alien.gif") folder or somewhere else (in which case, where)?
I can't reference any of the gifs (getting the fail msg I've implemented) Sad


ref = "sprites/homer.gif"

but when it gets to assigning URL, url = null
-_-
Offline Slyntax

Junior Devvie


Medals: 3



« Reply #5 - Posted 2013-09-24 21:58:45 »

I'm fairly certain this.getClass().getClassLoader().getResource(ref); will look in the root directory of your program

Lets say src, bin etc are in C:/SpaceInvaders

So...

1  
this.getClass().getClassLoader().getResource("sprites/homer.gif");


is pointing to C:/SpaceInvaders/sprites/homer.gif
Offline evil_error

Junior Newbie





« Reply #6 - Posted 2013-09-24 22:56:38 »

No Sad
I've attempted "src/sprites/homer.gif"
PLUS, in the mentioned tutorial, "sprites/image.gif" is used.
Hmm...
Offline evil_error

Junior Newbie





« Reply #7 - Posted 2013-09-24 23:01:06 »

SOLVED:
Moved sprites from src to bin;

when using
URL url = this.getClass().getClassLoader().getResource(reference);
the location of the reference is considered to be in the root (bin) folder of the project.

Thanks regardless!
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Mr.CodeIt (24 views)
2014-12-23 03:34:11

rwatson462 (55 views)
2014-12-15 09:26:44

Mr.CodeIt (45 views)
2014-12-14 19:50:38

BurntPizza (88 views)
2014-12-09 22:41:13

BurntPizza (111 views)
2014-12-08 04:46:31

JscottyBieshaar (82 views)
2014-12-05 12:39:02

SHC (92 views)
2014-12-03 16:27:13

CopyableCougar4 (99 views)
2014-11-29 21:32:03

toopeicgaming1999 (159 views)
2014-11-26 15:22:04

toopeicgaming1999 (157 views)
2014-11-26 15:20:36
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!