1

I am attempting to get an image to show up in a JPanel. Here is the code I'm using:

        URL imageURL;
        BufferedImage image = null;
        ImageIcon icon;

        imageURL = getClass().getClassLoader().getResource("images/audiorpglogo.png");
        if (imageURL == null) {
            System.out.println(imageURL == null);
            try { imageURL = new File("images/audiorpglogo.png").toURI().toURL(); }
            catch (Exception e1) { imageURL = null; }
        }

        System.out.println(imageURL == null);

        try { image = ImageIO.read(imageURL); }
        catch (Exception e) { }

        System.out.println(image == null);

        icon = new ImageIcon(image);

        System.out.println(icon == null);

        logo = new JLabel(icon);

When I run this program in Eclipse, I get the following output:

true
false
false
false

However, when I export the program as a runnable JAR, I get this following output:

true
false
true
java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:204)
    at me.pogostick29.audiorpg.window.Window.<init>(Window.java:85)
    at me.pogostick29.audiorpg.window.WindowManager.setup(WindowManager.java:16)
    at me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:30)

Thanks in advance for the help!

nrubin29
  • 1,522
  • 5
  • 25
  • 53
  • Changed `imageURL = getClass().getClassLoader().getResource("images/audiorpglogo.png");` to `imageURL = getClass().getClassLoader().getResource("/images/audiorpglogo.png");` and it didn't help. – nrubin29 Apr 13 '13 at 20:36

2 Answers2

1

You should have a resource folder with the folder named images in that, then it should work.

Example:

enter image description here

How I access those icons:

public BufferedImage icon32 = loadBufferedImage("/icon/icon32.png");
public BufferedImage icon64 = loadBufferedImage("/icon/icon64.png");

private BufferedImage loadBufferedImage(String string)
{
    try
    {
        BufferedImage bi = ImageIO.read(this.getClass().getResource(string));
        return bi;
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}
syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • I did that and it worked, but now I have this mess: http://icap.me/i/tZ43BrZ7fi.png – nrubin29 Apr 13 '13 at 21:00
  • Time for spring cleaning (code edition)! – syb0rg Apr 13 '13 at 21:01
  • So what do I do? Do I make an audio folder, then a locs subfolder, then move everything in? (etc) – nrubin29 Apr 13 '13 at 21:01
  • Yeah, I would make one `audio` folder, and just move all your stuff into that. It might be a lot (and even a little unorganized), but if you use file-names to sort the files alphabetically, you should be fine. – syb0rg Apr 13 '13 at 21:04
0

Try this code:

try { 
  InputStream in = getClass().getResource(imgName); //Read from an input stream 
  img = new ImageIcon(ImageIO.read(in));    
}catch (Exception e1) {
 e1.printStackTrace();
} 
olyanren
  • 1,448
  • 4
  • 24
  • 42