The Image
constructor is expecting the specification of a URL, not a file system path. Assuming you are bundling this image as part of your application, you will need to load that from the same place as your classes are loaded: probably a jar file in your final deployment, but perhaps from the file system during development.
The mechanism to get a URL representing a resource which is part of the application is to call getResource()
on a Class
or ClassLoader
.
The exact way to do this depends on your project structure, which you haven't shown, but for example:
new Image(getClass().getResource("Snake/Images/background_options.png").toString(), true);
will load the image from a resource, specified relative to the current class, and
new Image(getClass().getClassLoader().getResource("Snake/Images/background_options.png").toString(), true);
will load the image from a resource specified relative to the class path.
In the event you pass a String
that represents a relative URL (i.e. one with no scheme, such as file:
, http:
, or jar:
), then the Image
constructor will search on the class path for the resource. In other words
new Image("Snake/Images/background_options.png", true);
is equivalent to
new Image(getClass().getClassLoader().getResource("Snake/Images/background_options.png").toString(), true);
This seems slightly counter-intuitive (to me, at least), so I prefer to always specify a URL completely, or to retrieve one from getClass().getResource()
or File.toURI().toURL()
as appropriate.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…