Cannot load image in JavaFX

Simply replace this code:

Image img = new Image("logo.png");

with this

Image img = new Image("file:logo.png");

Docu reference.
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/Image.html

When you pass a String to the Image class it can be handled in four different ways (copied from docu):

// The image is located in default package of the classpath
Image image1 = new Image("/flower.png");

// The image is located in my.res package of the classpath
Image image2 = new Image("my/res/flower.png");

// The image is downloaded from the supplied URL through http protocol
Image image3 = new Image("http://sample.com/res/flower.png");

// The image is located in the current working directory
Image image4 = new Image("file:flower.png");

The file: prefix is simply an URI scheme, or in other words the counterpart to the http: protocol classifier. This also works in the file browser, or in the web browser… 😉

For further reference, you can take a look at the wiki page of the file URI scheme: https://en.wikipedia.org/wiki/File_URI_scheme

Happy Coding,

Kalasch

Leave a Comment