-1

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.

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm using IntelliJ 13.0.1, tried it both with absolute and relative path files, didn't work.
Nevermind, apparently using an absolute path will not make it work. I moved the files around and it's fine now, thanks!
No problem, I'm glad it is sorted.
1

Pass the path directly like this.

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

I dont know, how MineSweeper is helpful here

1 Comment

That's the name of the project that I'm working on, I got it to work though thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.