Java GUI程序Jar转Exe后图片加载失败问题求助
Hey there, let's break down why your image loading is failing post-packaging and walk through how to fix it:
The Root Cause
That NullPointerException stems from a path mismatch once your code is bundled into a Jar (and converted to Exe via JSmooth). In Eclipse, the relative path ../images/intro.jpg works because the IDE treats your project's source/resource directories as part of the classpath root. But when packaged into a Jar, all resources get bundled directly into the classpath root—so the ../ relative path becomes invalid, making getResource() return null and crashing the ImageIcon initialization.
Step-by-Step Fixes
1. Adjust Resource Structure & Loading Code
- First, move your
imagesfolder into your source directory (e.g., if yourMain.javais in thetestpackage, placeimagesundersrc/test/so it sits alongside your class files). This ensures it gets included in the Jar during packaging. - Update your image loading code to use a classpath-absolute path (drop the
../):
introBackground = new ImageIcon(Main.class.getResource("/test/images/intro.jpg")).getImage();
If the images folder is directly inside the same package as Main, you can simplify it to:
introBackground = new ImageIcon(Main.class.getResource("images/intro.jpg")).getImage();
2. Verify Jar Contents
After exporting the Jar from Eclipse, open it with a zip tool to confirm images/intro.jpg is in the correct location (e.g., alongside test/Main.class). If it's missing, double-check your export settings to ensure resource files are being included.
3. JSmooth Configuration Checks
- In JSmooth, confirm you've selected the correct Jar file path, and enable the option to include all classpath dependencies (if any) to avoid missing resources.
- Set the working directory to your Exe/Jar's location in JSmooth's settings—this prevents the program from searching for resources in the wrong folder at runtime.
Alternative: Load External Images
If you want to keep images outside the Jar (for easy updates), place the images folder in the same directory as your Exe, then load using a file path instead:
File imageFile = new File("images/intro.jpg"); introBackground = new ImageIcon(imageFile.getAbsolutePath()).getImage();
Just remember to include the images folder when distributing your Exe.
内容的提问来源于stack exchange,提问作者dongwon shin

