我正在尝试通过相对路径检索图片,但是无论我尝试使用哪种路径组合,它始终会返回java.lang.NullPointerException

private final Icon cardBack = new ImageIcon(getClass().getResource(
    "src/main/resources/Images/cardIcons/cardBack.png"));


java - 无法通过相对路径检索图像-LMLPHP

https://pastebin.com/sDjP87p3

最佳答案

我相信NPE是从ImageIcon构造函数抛出的,因为getResource返回null。

请尝试以下操作:

private final Icon cardBack = new ImageIcon(getClass().getClassLoader().getResource("src/main/resources/Images/cardIcons/cardBack.png"));


要么:

private final Icon cardBack = new ImageIcon(ClassLoader.getSystemResource("src/main/resources/Images/cardIcons/cardBack.png"));

09-26 02:33