Domanda

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

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top