简体   繁体   English

使用getResource()无法获取图像

[英]Can't get images working, with getResource()

I'm trying to make a jar, but the program needs images. 我试图做一个罐子,但是程序需要图像。 When I ran the jar, the images didn't show up. 当我运行广口瓶时,图像没有显示。 However, they did in eclipse. 但是,他们确实在日食中。 I used this code: 我使用以下代码:

label.setIcon(new ImageIcon("res/img/icon.png"));

Then I went looking on the internet for a way to fix it. 然后我去互联网上寻找解决方法。 I found this question here on StackOverflow, but when i tried it in my code, it's throwing a NullPointerException (also in eclipse). 我在StackOverflow上找到了这个问题,但是当我在代码中尝试问题时,它抛出了NullPointerException (也在eclipse中)。 This is my code now: 现在是我的代码:

label.setIcon(new ImageIcon(getClass().getResource("/res/img/icon.png")));

The images are in a separate folder in the package, called "res": 图像位于程序包中的单独文件夹中,称为“ res”:

在此处输入图片说明

  1. create a package inside your project, and name it something like "Images". 在您的项目中创建一个程序包,并将其命名为“ Images”。
  2. Now, add images you are using into this package. 现在,将要使用的图像添加到该程序包中。
  3. Finally, call to these images, which are inside the package. 最后,调用包装内的这些图像。

make sure you typed image names correctly as well 确保您也正确键入了图像名称

That is the best way of dealing with images 那是处理图像的最好方法

update 更新

try 尝试

label.setIcon(new ImageIcon(getClass().getResource("res/img/icon.png")));

instead of 代替

label.setIcon(new ImageIcon(getClass().getResource("/res/img/icon.png")));

Have a look that your RES folder is actually within the eclipse SRC folder. 看一下您的RES文件夹是否确实在Eclipse SRC文件夹中。 Sometimes, users add a folder to the eclipse project instead. 有时,用户会将文件夹添加到eclipse项目中。

Also: 也:

  • Try cleaning and rebuilding your project. 尝试清理并重建项目。
  • In Eclipse, open the Navigator view. 在Eclipse中,打开Navigator视图。 Open the /bin folder of the project. 打开项目的/ bin文件夹。 Does it have the /res/img/icon.png ( comment from here ) 它是否具有/res/img/icon.png (来自此处的评论)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM