[英]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
. Class#getResource
将传递给它的路径视为相对于类包的路径,因此在您的情况下,它正在查找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")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.