2014-12-02 101 views
0

我有一個問題,所以我會在下面顯示它。首先,感謝您的閱讀!在Netbeans編碼一個掃雷遊戲。在代碼中,我必須包括數字,炸彈,標誌的圖像...在Java中包含圖像

首先,我在「src」中創建了一個「images」文件夾。然後我去屬性,並添加資源(它顯示項目中的圖像文件夾)。

我的工作區:https://flic.kr/p/qevcEm

那麼這是很重要的,我搜索谷歌和使用此代碼,但得到了麻煩。

public void imgmine() { 
    String name; 


    for (int i = 0; i <= 8; i++) { 
     name = "images/" + i + ".png"; 
     ic[i] = new ImageIcon(this.getClass().getResource(name)); 
     /// i was edit above line. but 9 10 11 12 13 wasnt. 
    } 
    ic[9] = new ImageIcon("bomb.png"); 
    ic[10] = new ImageIcon("flag.png"); 
    ic[11] = new ImageIcon("newgame.png"); 
    ic[12] = new ImageIcon("crape.gif"); 
    ic[13] = new ImageIcon("winner.gif"); 
} 

在windows代碼中沒有錯誤。但是編者說:

Exception in thread "main" java.lang.NullPointerException 

    at javax.swing.ImageIcon.<init>(ImageIcon.java:205) 

    at Minesweeper.imgmine(Minesweeper.java:522) 

    at Minesweeper.<init>(Minesweeper.java:43) 

    at Main.main(Main.java:32) 

Java Result: 1 
BUILD SUCCESSFUL (total time: 1 second) 

522線是

ic[i] = new ImageIcon(this.getClass().getResource(name)); 
+0

'Minesweeper.class'的FQN是什麼? – PeterMmm 2014-12-02 15:35:19

+0

什麼是FQN先生?我的英文不是很好:( – TruongHieu 2014-12-02 15:40:22

+0

[FQN](http://en.wikipedia.org/wiki/Fully_qualified_name)like'my.package.game.Minesweeper'。 – PeterMmm 2014-12-02 15:41:54

回答

2

使用絕對路徑,如getClass().getResource(...)給出的相對根包的目錄。

name = "/images/" + i + ".png"; 

P.S.

Are not bomb.png and other not in images /?

+0

ic 9 10 11 12 13 >>我沒有編輯它,我在ic [i]第一次測試。文件夾是:C:\ Users \ hieut_000 \ Documents \ NetBeansProjects \ Minesweeper \ src \ images – TruongHieu 2014-12-02 15:41:23

+0

在生成的應用程序jar(zip檔案)中,您應該找到'/ images/0.png'路徑, Class.getResource' – 2014-12-02 15:46:59

+0

我認爲它不能被編譯的問題。所以我不能找到圖像文件夾在jar – TruongHieu 2014-12-02 15:50:50