如何从 NetBeans 的“Resources"文件夹中正确获取图像 [英] How to correctly get image from 'Resources' folder in NetBeans
问题描述
我在 NetBeans 7.0 中有一个 Java 项目.
I have a Java Project in NetBeans 7.0.
我想动态地向某个标签添加一些图像.图像将根据程序的状态而有所不同.
I want to add some image to some label dynamically. The image will differ depending on the state of the program.
我在我的项目的资源"文件夹中放了一张这样的图片filling.jpg".
I put one such image, 'filling.jpg', in the 'resources' folder of my project.
我想正确地访问这个文件(不是通过绝对或相对路径,因为这会在我构建 jar 文件时导致问题).
I want to reach this file correctly (not by absolute or relative path, because that will cause problems when I build the jar file).
于是我找到了这个方法:
So I found this method:
ImageIcon fillingIcon = new ImageIcon(getClass().getClassLoader().getResource("filling.jpg"));
labelFontFilling.setIcon(fillingIcon);
它一直给我 java.lang.NullPointerException.但我确信有那个图像,因为我可以从 NetBeans 属性菜单中为该标签将图像分配给标签(但我不想要这个,我想通过 Java 代码添加图像).
It keeps give me java.lang.NullPointerException. But I am sure that there is that image, because I can assign the image to the label from the NetBeans Properties menu for that label (but I don't want this, I want to add the image by Java code).
我做错了什么,如何正确获取该图像?
What am I doing wrong, and how can I get that image correctly?
推荐答案
谢谢,Valter Henrique,根据您的提示,我意识到我只是输入了错误的图片路径.在我的一次尝试中,我使用
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
但正确的方法是在资源路径中使用我的项目名称
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
这篇关于如何从 NetBeans 的“Resources"文件夹中正确获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!