0

(First of all, I'm sorry If there is like a million questions like this. I've tried everything I can and this is driving me nuts!)

I'm trying to had an icon to a JButton but I keep getting an IllegalArgumentException caused by ImageIO.

Here's what I have:

    //Other UI elements ^
    JButton X = new JButton("Clear");        
    //com.oliveira.ux is the package name
    Image img = ImageIO.read(getClass().getResource("/com.oliveira.ux/resource/gtk-clear.png"));
    Icon clear = new ImageIcon(img);
    //More UI elements

The Icon is located under src/PACKAGE NAME/resource/. (I use eclipse). I've tried to change the location on the code above (the one I wrote here was the last one I tried) but all I get is an IllegalArgumentException when I run de .jar. Any suggestions?

Many thanks in advance

Here's the full error message:

Caused by: java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(Unknown Source)
    at com.oliveira.ux.Main.<init>(Main.java:146)
    at com.oliveira.ux.Main.main(Main.java:75)
    ... 5 more

This points to the ImageIO part in the code I wrote above.

Luso
  • 125
  • 2
  • 9
  • Please post the complete stack trace, along with any "caused by" sections, and indicate the statement in your code that is throwing the exception. – Jim Garrison Aug 16 '13 at 23:34
  • 1
    `getClass().getResource()` looks for a file relative to the current class's location, so if your class is already inside of the com.oliveira.ux package, then you only need to pass it `"resource/gtk-clear.png"`. As an aside, packages are folders, so com should be a folder, oliveira should be a subfolder, and so on; therefore, you would do something like com/oliveira/blah/blah. – sgbj Aug 16 '13 at 23:37
  • 1
    Is this `com.oliveira.ux` suppose to be a web reference or a package path reference. If it's a path, it should not be separated by `.` but `/` – MadProgrammer Aug 16 '13 at 23:43
  • @sbat that did it, thank you! I thought it was separated by dots because of eclipse... Didn't even remember of checking the file system. Anyway thanks – Luso Aug 16 '13 at 23:48
  • @MadProgrammer it's the package name – Luso Aug 16 '13 at 23:50
  • @Luso : Please have a look at this [answer](http://stackoverflow.com/questions/8960381/runnable-jars-missing-images-files-resources/9278270#9278270). Hopefully this might be able to help a bit :-) – nIcE cOw Aug 17 '13 at 02:24

1 Answers1

3

The path appears to be wrong...

Image img = ImageIO.read(getClass().getResource("/com.oliveira.ux/resource/gtk-clear.png"));

getResource isn't expecting the pack name, but the "path" to the resource from the context of the class path (so the path is appended to the class path elements)

Something like...

Image img = ImageIO.read(getClass().getResource("/com/oliveira/ux/resource/gtk-clear.png"));

Should give a better result

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366