简体   繁体   English

getClass()。getResource(…)找不到我的图片

[英]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.

相关问题 VLCJ 在使用 getClass().getResource() 时不播放视频 - VLCJ doesn't play video when using getClass().getResource() getClass().getResource(..) 使图像图标突然为空 - getClass().getResource(..) makes image icon suddenly null 为什么我的`getClass()。getResource(“ logs”)`返回null? - why is my `getClass().getResource(“logs”)` returns null? getClass()。getClassLoader()。getResource()在OC4J App Server中不起作用 - getClass().getClassLoader().getResource() Doesn't work in OC4J App Server 为什么我可以从getClass()。getResource()获取有效的url,但是返回的url创建了一个不存在的文件 - Why can I get a valid url from getClass().getResource(), but the url that is returned creates a file that doesn't exist 在NetBeans中创建jar文件后,ImageIcon图标=新的ImageIcon(getClass()。getResource(String))不起作用 - ImageIcon icon = new ImageIcon(getClass().getResource(String)) doesn't work after creating jar file in netbeans Java getClass()。getClassLoader()。getResource(“ /My_Form.xsd”)返回null - Java getClass().getClassLoader().getResource( “/My_Form.xsd”) returns null 如何使用getClass和getResource? - How to use getClass and getResource? getClass()。getResource + Tomcat + Hibernate - getClass().getResource + Tomcat + Hibernate getClass() getResource 返回 null - getClass() getResource returning null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM