2013-04-08 84 views
2

我试图访问我的Java代码中的一些图像。下面是调用图像的代码。访问Eclipse中的图像路径

public final ImageIcon whitePiece = new ImageIcon(getClass().getResource("Images/whitecircle.PNG")); 
public final ImageIcon blackPiece = new ImageIcon(getClass().getResource("Images/blackcircle.png")); 
public final ImageIcon tiePiece = new ImageIcon(getClass().getResource("Images/tiecircle.PNG")); 
public final ImageIcon boardPic = new ImageIcon(getClass().getResource("Images/gameboard.PNG")); 

然而,这将返回以下错误:

Exception in thread "main" java.lang.NullPointerException 
    at javax.swing.ImageIcon.<init>(Unknown Source) 
    at jared.othello.GameInterface.<init>(GameInterface.java:26) 
    at jared.othello.Main.main(Main.java:22) 

线26上面的代码中的第一行。我几乎肯定我的文件目录命名有问题,但我无法弄清楚有什么问题或如何解决它。我已经建立了我的项目中名为“图像”源文件并放在影像的文件夹中,像这样:

Project Configuration

我在做什么错,什么是正确的文件名语法?谢谢!

+1

你需要在图像路径中领先的'/'? – 2013-04-08 21:52:36

+0

不,我把它拿出来了,但代码仍然不起作用。 – 2013-04-08 21:55:06

+0

您需要创建另一个源路径,并将图像文件夹放在其中。然后确保Eclipse将这些资源包含在已编译的工件中,因为有时候Eclipse会添加一些过滤器来阻止某些文件出现在您的构建中。 – 2013-04-08 21:56:21

回答

5

你应该有一个名为Images的文件夹的资源文件夹,那么它应该工作。

例子:

enter image description here

我如何访问这些图标:

public BufferedImage icon32 = loadBufferedImage("/icon/icon32.png"); 
public BufferedImage icon64 = loadBufferedImage("/icon/icon64.png"); 

private BufferedImage loadBufferedImage(String string) 
{ 
    try 
    { 
     BufferedImage bi = ImageIO.read(this.getClass().getResource(string)); 
     return bi; 
    } catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    return null; 
} 
+0

我试过了(看我的编辑),它似乎没有工作。任何想法为什么? – 2013-04-08 21:59:59

+0

然后你的文件树应该看起来与我答案中的极其相似,并且每个文件夹图标都应该是相同的。另外,访问它们时应该有'/'前导。 – syb0rg 2013-04-08 22:03:40

+3

领先的'/'必需? – 2013-04-08 22:04:44

1

尝试导入图像的路径是你 “的.java” 源文件的位置。在eclipse中尝试以下内容: 右键点击你的“.java”文件,选择Import-> File System-> From Directory(提供图像所在的路径) - >选择图像,然后单击Finish。

您可以看到“.java”源所在路径中列出的图像。您可以在代码中直接使用图像文件名称。 谢谢, P