问题
I'm trying to access some images in my Java code. The code to call the images is below.
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"));
However, this returns the following error:
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)
Line 26 is the first line of the above code. I am almost positive that something is wrong with my file directory naming, but I can't figure out what's wrong or how to fix it. I've created a source file named 'Images' within my project and placed the images in the folder, like so:
What am I doing wrong, and what is the correct filename syntax? Thanks!
回答1:
You should have a resource folder with the folder named Images
in that, then it should work.
Example:
How I access those icons:
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;
}
回答2:
Try importing the images to the path were your ".java" source file is located. Try below in eclipse: right click on your ".java" file, select Import->File System->From Directory(provide the path where images are located)->Select the images and click Finish.
You can see the images getting listed in the path where ".java" source is located. You can directly use the image file name in you code. Thanks, P
来源:https://stackoverflow.com/questions/15889608/accessing-image-paths-in-eclipse