2013-05-26 74 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

相關問題