Java getClass().getResource在png上返回Null指针 [英] Java getClass().getResource on a png returning Null Pointer
问题描述
我不确定我是否用此代码引用正确的位置,我尝试访问的图像标题为Flower0.png
等.
I am not sure if I am referring to the right location with this code, the images I am trying to access are titled Flower0.png
etc.
它们与该项目的其余代码位于同一目录中.
此类位于名为hangman.ui
的src文件夹中,而.png
文件位于名为Resources
的目录文件夹中.
They are located in the same directory as the rest of my code for this project.
This class is in a src folder called hangman.ui
and the .png
files are located in a directory folder called Resources
.
也许getClass().getResource
是不对的?
这是我第一次尝试将图像放入GUI.
This is my first time trying to put images into a GUI.
非常感谢您的帮助!
public WiltingFlowerRendererRemix(HangmanLogic logic)
{
panel = new JPanel();
panel.setLayout(new BorderLayout());
imageLabel = new JLabel();
panel.add(imageLabel, BorderLayout.CENTER);
int numberOfImages = 10;
images = new ImageIcon[numberOfImages];
for (int i = 0; i < numberOfImages; i++)
{
images[i] = new ImageIcon(getClass().getResource("Flower"+Integer.toString(i) + ".png"));
}
}
推荐答案
您说图像位于名为资源"的文件夹中吗?您可以这样加载图像:
You say the images are in a folder called "Resources"? You can load images like this then:
BufferedImage image = ImageIO.read(getClass().getResource("/Resources/Flower0.png"));
ImageIcon icon = new ImageIcon(image);
要在GUI上使用它,可以使用JLabel.
To use it on the GUI you can use a JLabel.
JLabel label = new JLabel();
label.setIcon(icon);
然后将标签添加到面板中.
And then add the label to a panel for example.
这篇关于Java getClass().getResource在png上返回Null指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!