简体   繁体   中英

getClass().getResource(…) doesn't find my image

I run my application and I get the following exception.

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:167)
    at view.View.getBookmarkPanel(View.java:162)
    ...

The source of the error is here.

JButton addButton = new JButton(new ImageIcon(this.getClass().getResource("img/plus.png")));

I understand that the exception implies that it cannot allocate the requested image through the provided directory, stating that the image doesn't exist. This confuses me because the image does exist.

My Documents\workspace\PersonalProjectUpdate\src\main\resources\img\plus.png

The code was working fine until I organised my files into packages, even after I undid this change the error is still occurring, however it shouldn't affect how the application allocates files from the resource folder.

Why is it doing this, can someone help me please?

Class#getResource treats the path you pass to it as relative to the class's package, so in your case it is looking for src\\main\\resources\\view\\img\\plus.png .

To solve this issue, add a leading slash to indicate that the path is absolute:

JButton addButton = new JButton(new ImageIcon(this.getClass().getResource("/img/plus.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