ImageIcon 打成Jar包后图片失效问题 classPathResource.getURL() Kaki的博客
需求是这样的,我的jar包内部程序是一个图形界面工具,引入了几个图片,使用ImageIcon,如果是IDE项目中使用new ImageIcon(this.getClass().getResource("/photos/111.png")),图片是可以正常访问的。但如果把项目打成jar包,运行在客户电脑上,就无法访问图片,也就是该方法 this.getClass().getResource 失效了。
经过查看了一系列CSDN大佬们写的博客,其中一位大佬说可以用ClassPathResource这个类,但大佬用的又是IO相关的操作,并且这个类我的项目没有,不知道是哪个maven坐标下的,这里说一下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>任意</version>
</dependency>
PS:纯手敲,可能有打错,用时请注意哈
将这个jar包引进来后,项目就有ClassPathResource了,然后我使用如下代码
ClassPathResource classPathResource = new ClassPathResource("/photos/111.png");
ImageIcon icon = new ImageIcon(classPathResource.getURL());
之后这个图片对象就能用了
码云直通车
欢迎码云,B站,ins 关注KakiNakajima