如何从NetBeans中的“Resources”文件夹中正确获取图像 [英] How to correctly get image from 'Resources' folder in NetBeans

查看:133
本文介绍了如何从NetBeans中的“Resources”文件夹中正确获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NetBeans 7.0中有一个Java项目。



我想动态地将一些图像添加到某个标签。根据程序的状态,图像会有所不同。



我在项目的'resources'文件夹中放了一个这样的图像'filling.jpg'。 / p>

我想正确地访问这个文件(不是通过绝对或相对路径,因为这会在我构建jar文件时引起问题)。



所以我找到了这个方法:

  ImageIcon fillingIcon = new ImageIcon(getClass()。getClassLoader() .getResource( filling.jpg)); 
labelFontFilling.setIcon(fillingIcon);

它一直给我java.lang.NullPointerException。
但我确信有那个图像,因为我可以从NetBeans Properties菜单中为该标签分配图像(但我不想这样,我想用Java代码添加图像) 。



我做错了什么,我怎样才能正确地获得该图像?

解决方案

谢谢, Valter Henrique ,你的提示我设法意识到,我只是输入了错误的路径到这个图像。
在我的一次尝试中,我使用

  String pathToImageSortBy =resources / testDataIcons / filling.png; 
ImageIcon SortByIcon = new ImageIcon(getClass()。getClassLoader()。getResource(pathToImageSortBy));

但正确的方法是在资源路径中使用我的项目名称

  String pathToImageSortBy =nameOfProject / resources / testDataIcons / filling.png; 
ImageIcon SortByIcon = new ImageIcon(getClass()。getClassLoader()。getResource(pathToImageSortBy));


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.

I put one such image, 'filling.jpg', in the 'resources' folder of my project.

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);

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?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆