-2

Whenever i try to draw an image with paintComponent and ImageIcon i get a NullPointerException from an unknown source, then pointing to my image getter and the thread start.

Image getter

ImageIcon image = new ImageIcon(this.getClass().getResource("C:/Users/Rhys/Desktop/workspace/Mindcracker RPG/Res/Background.jpg"));

Thanks for any answers

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2687097
  • 17
  • 1
  • 6
  • 2
    Is the file path valid? – nhgrif Dec 07 '13 at 21:48
  • Yes it is, i tried using the / and the \\ aswell between each path – user2687097 Dec 07 '13 at 21:51
  • 1
    Well, you should have seen enough Q&As to realize we need to know a) The root of the class-path b) that a path prefixed with a drive letter won't find anything using that method. – Andrew Thompson Dec 07 '13 at 21:51
  • So what should my path be ?? Referenced from the internet or a File e.g. File file = new File(); – user2687097 Dec 07 '13 at 21:54
  • Are you sure you need to use this.getClass().getResource("FileName") instead of new ImageIcon("FileName")...? – Sameer Sawla Dec 07 '13 at 21:55
  • Yeah, i tried what you said before, ill try again Just a blank screen :( – user2687097 Dec 07 '13 at 21:56
  • Use the JavaDoc it is your friend and explains exactly how to do what you want! –  Dec 07 '13 at 22:04
  • For tips see the [embedded-resource info. page](http://stackoverflow.com/tags/embedded-resource/info). One major tip. Always prefix the path with `/` (the root of the class-path) to account for resource access from code in packages. Keep using `getResource(..)` for an URL rather than `String` for a `File`. That is an (at best) temporary solution. Tip: Add @SameerSawla (or whoever - the `@` is important) to notify someone of a new comment. – Andrew Thompson Dec 07 '13 at 23:45

1 Answers1

1

Use the JavaDoc:

this.getClass().getResource() only for acquiring resources on the ClassPath where / represents the default package.

You are supplying a fully qualified path which won't work.

What you need to do is use this constructor:

public ImageIcon(String filename) 

Creates an ImageIcon from the specified file.

The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.)

For example, specify:

new ImageIcon("C:/Users/Rhys/Desktop/workspace/Mindcracker RPG/Res/Background.jpg");

note that there is a space in the path there and this path eventually gets converted into a file::// URL so you might want to take that into consideration