Cannot load image in JavaFX


I tested this code in order to create dialog with image.

final int xSize = 400;
final int ySize = 280;
final Color backgroundColor = Color.WHITE;
final String text = "SQL Browser";
final String version = "Product Version: 1.0";

final Stage aboutDialog = new Stage();

Button closeButton = new Button("Close");

closeButton.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent arg0) {

GridPane grid = new GridPane();
grid.setPadding(new Insets(25, 25, 25, 25));

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

grid.add(imgView, 0, 0);

grid.add(new Text(text), 0, 1);
grid.add(new Text(version), 0, 2);
grid.add(closeButton, 14, 18);

Scene aboutDialogScene = new Scene(grid, xSize, ySize, backgroundColor);

I placed the image file into the directory /src. But for some reason the image is not displayed. Can you help me to correct my mistake?

4/19/2013 8:07:15 AM

Accepted Answer

Simply replace this code:

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

with this

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

Docu reference.

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("");

// 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:

Happy Coding,


6/4/2019 7:58:12 AM

Try this:

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

If no protocol part indicating a URL (as http: or file:) is given, the file is supposed to reside in the default package. If you want it to put in a different package say you add this information in a path like manner:

img = new Image("/com/my/images/logo.png");

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow