简体   繁体   中英

ClassLoader.getResource() doesn't work from .jar file

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.

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.

用它来获取jar文件中的图像

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM