2014-12-02 129 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