Question

I'm trying to get an image to use in a JButton, with the code:

ImageIcon imageIcon = new ImageIcon(MineSweeper.class.getResource("C:\\Users\\___\\Documents\\GitHub\\____\\myImage.png"));
buttons[x][y].setIcon(imageIcon);

I know the file exists there, however every time I run it I get the error,

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:205)

Which after looking around says that is the response for not being able to find the file, I'm confused as to what I'm doing wrong here. I get this error if I try to use absolute or relative paths, can someone point out what's wrong? I must be over looking something really simple here.

EDIT:

As Alan suggested to move the file, I put it into the src folder and it worked fine. Apparently having it else where won't work.

Was it helpful?

Solution

Try something like this for setting the image icon

ImageIcon imageIcon = new ImageIcon(getClass().getResource("myImage.png"));

Your image file should be located within the src folder if your using an IDE. If your not using an IDE , put the image in the same folder as your .java files.

OTHER TIPS

Pass the path directly like this.

ImageIcon image = new ImageIcon("c://somepath//image.png");

I dont know, how MineSweeper is helpful here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top