Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.(ImageIcon.java:205)
at ExampleFrame_03.(ExampleFrame_03.java:30)
at ExampleFrame_03.main(ExampleFrame_03.java:14)
第 30 行 new ImageIcon(resource) 拋出 NPE,說明 resource == null,即 getResource("/back.jpg") 未找到資源。
back.jpg 在源碼目錄下,且 IDE 設置將資源文件複製到 classes/bin 目錄。getResource("/back.jpg") 從 classpath 根目錄查找。若代碼在包 com.example,資源需放在 src/back.jpg(Maven: src/main/resources/back.jpg),而非 src/com/example/back.jpg。pom.xml / build.gradle 是否包含 <resources> 配置。back.jpg 而非 Back.jpg。URL resource = this.getClass().getResource("/back.jpg");
System.out.println("Resource URL: " + resource); // null 即未找到
if (resource == null) {
// 列出 classpath 根目錄實際內容
Enumeration<URL> roots = this.getClass().getClassLoader().getResources("");
while (roots.hasMoreElements()) {
URL root = roots.nextElement();
System.out.println("Classpath root: " + root);
try (Stream<Path> files = Files.walk(Paths.get(root.toURI()))) {
files.filter(p -> p.toString().endsWith(".jpg")).forEach(System.out::println);
} catch (Exception ignored) {}
}
}
URL resource = this.getClass().getResource("/back.jpg");
if (resource == null) {
throw new IllegalStateException("找不到資源 /back.jpg,請檢查資源目錄配置");
}
ImageIcon icon = new ImageIcon(resource);
// ... 後續代碼