2013-05-26 64 views
0

我不知道如果我指到正确的位置,此代码,我试图访问的图像标题Flower0.png的Java的getClass()的getResource在PNG返回NULL指针

它们位于与我的这个项目的其他代码在同一个目录中。 该课程位于名为hangman.ui的src文件夹中,而.png文件位于名为Resources的目录文件夹中。

也许getClass().getResource是不正确的?

这是我第一次尝试将图像放入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")); 

    } 
} 
+0

资源路径必须以'/'开头。尝试'“/花”'。 – fge

+0

谢谢,现在我无法看到图像。我把它设置为可见,我只是不知道... – jessicaeden

+0

你也可以看看.. http://stackoverflow.com/questions/2343187/loading-resources-using-getclass-getresource – awsome

回答

1

你说这些图像位于一个名为“Resources”的文件夹中?您可以像这样加载图像:

BufferedImage image = ImageIO.read(getClass().getResource("/Resources/Flower0.png")); 
ImageIcon icon = new ImageIcon(image); 

要在GUI上使用它,您可以使用JLabel。

JLabel label = new JLabel(); 
label.setIcon(icon); 

然后将标签添加到面板中。

+1

的文件名资源不必以“/”开头(如在另一个答案中声明);如果他们确实以/开头,则该路径相对于类路径上的某个路径;如果他们不这样做,他们是与该类别所在的目录相关的。因此,没有任何斜线的“x.png”将在与调用getResource的类相同的目录中查找,“y/x.png”将在目录y中查找,该目录是目录下的子目录这个班活着。 – arcy

相关问题