3

I have the following code:

private final ImageIcon placeHolder = new ImageIcon(this.getClass().getClassLoader().getResource("Cards\\trans.png"));

But this does not work once my application exported into a .jar file.

JRL
  • 76,767
  • 18
  • 98
  • 146
Patrick
  • 151
  • 2
  • 2
  • 4

2 Answers2

10

Your "\t" is being compiled as a tab - you need to escape it:

private final ImageIcon placeHolder = new ImageIcon(
    this.getClass().getClassLoader().getResource("Cards\\trans.png"));

Note the double backslash. This may not be the only thing wrong, of course - but it's a start...

In fact, I would specify it with a forward slash instead. That works on both Windows and Unix-based OSes anyway, and it also works with jar files. The only reason I highlighted the double backslash was to raise the point of string escaping in general. Try this:

private final ImageIcon placeHolder = new ImageIcon(
    this.getClass().getClassLoader().getResource("Cards/trans.png"));

Next, make sure you've got the exact correct name for the file, including case. Even though Windows file systems aren't generally case-sensitive, jar files are. If it's actually "cards" instead of "Cards" or "TRANS.png" instead of "trans.png", it won't work.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is there a reason you call getResource on the ClassLoader instead of just the class? (i.e. won't getClass().getResource() work? ) – JRL Nov 02 '09 at 22:28
  • @JRL: If you call it from the classloader it's relative to the root of the jar file rather than to the class. You can use a leading slash to get the same effect from a call to Class.getResource though. – Jon Skeet Nov 02 '09 at 23:01
4

Use this for getting images in jar file

ClassLoader.getSystemResource("images/Springz3.png"));

  • 1
    oh. em. gee. You have no idea how long I was looking for this answer. Everybody keeps saying to use getResource(..), but that doesn't work for images/sounds in a jar file! You have to use getSystemResource(..)!!!!! Thanks a ton for this answer! – BigSauce Dec 08 '13 at 18:42
  • No mention please. – Basil C Sunny Apr 06 '17 at 16:04