0

I want to ask about a problem in my project: I have a class that extends JFrame, and I want to change the Java icon on that frame to another icon using this code:

setIconImage(new ImageIcon(getClass().getResource("icon.PNG")).getImage());

I'm using NetBeans, and when I run my project from NetBeans, it runs normally, but when I run it from the jar, it does not run. Then, when I remove that code, my jar runs normally with the Java icon in the frame.

Can anyone can tell me what might be wrong with that code?

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
ZeeDroid
  • 145
  • 1
  • 11
  • 2
    That's a very poor question title. – SLaks Jan 30 '12 at 05:31
  • 2
    The first thing that comes to mind is that the icon.PNG might not be getting packed into the jar, or some other kind of path issue could be happening. Are you getting any error messages? – Corbin Jan 30 '12 at 05:32
  • I'm sorry with my question title before,I'm newbie with this and my English is very bad.. no, i don't get any error when i start that jar,,, – ZeeDroid Jan 30 '12 at 05:38
  • 1
    Why does `"icon.PNG"` have an upper case extension? Note that Java is case sensitive, so if the name is `Icon.png`, that is **exactly** how it needs to be written. – Andrew Thompson Jan 30 '12 at 05:39
  • @SLaks First thing I thought when I read that was "does it have legs?" – Etienne de Martel Jan 30 '12 at 05:40
  • name of file is icon.PNG, so i write icon.PNG.. – ZeeDroid Jan 30 '12 at 05:46
  • Thanks for confirming. Please note that I only get notified of your comment if you start it with @AndrewThompson (type @and & a small pop-up will appear - click on it to insert the entire name). 1) Is the `JFrame` in a pack (if so, what package?) 2) Where is the icon in relation to the class? (The way the String argument is formed, it would need to be located in that package). 3) .. – Andrew Thompson Jan 30 '12 at 06:06
  • .. 3) As an aside, you are using a kind of shortcut that I feel is not that sensible for broken code. I would: a) Establish the URL using `Class.getResource()` b) Check the `URL` using a debugger or `println(URL)` c) Use `ImageIO.read(URL)` to load the image (throws lots of helpful exceptions) d) Call `setIconImage(Image)`. – Andrew Thompson Jan 30 '12 at 06:07

1 Answers1

0

When running jar file you cannot access files by using:

getClass().getResource("...")

You should use:

getClass().getResourceAsStream("...")

See: File loading by getClass().getResource()

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Nick
  • 744
  • 6
  • 11