-1

I'm trying to open an image in JavaFX and am getting this error

Caused by: java.io.FileNotFoundException: calibre/Books/1.png (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)

I think i'm getting my directories wrong somehow.

This is the method where I create the image.

public class Calibre extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        FileInputStream input = new FileInputStream("calibre/Books/1.png");
        Image image = new Image(input);
        ImageView imageView = new ImageView(image);

        HBox hbox =  new HBox(imageView);

        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        root.setId("pane");
        Scene scene = new Scene(root);
        stage.setScene(scene);
        scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
        Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
        //Set Stage Boundaries to visible bounds of the main screen
        stage.setX(primaryScreenBounds.getMinX());
        stage.setY(primaryScreenBounds.getMinY());
        stage.setWidth(primaryScreenBounds.getWidth());
        stage.setHeight(primaryScreenBounds.getHeight());
        stage.show();
    }

File Directory

This is my directory, as you can see my images are stored inside.

Any help is greatly appreciated.

Argon
  • 55
  • 1
  • 7

1 Answers1

1

Images that are part of your application are resources, not files. They will be deployed along with the class files when your application is built (e.g. they will be copied to the build folder, or included in the jar file, depending on how you build the application).

The FileInputStream you construct will be relative to the current working directory, and you have no control over what that will be at runtime.

Instead of using a stream, use the Image constructor that takes a URL, in the form of a string. This will be resolved relative to the classpath:

    // FileInputStream input = new FileInputStream("calibre/Books/1.png");
    Image image = new Image("/calibre/Books/1.png");

If you really want to supply a Stream, for some reason, you can get the stream from the resource:

    InputStream input = getClass().getResourceAsStream("/calibre/Books/1.png");
    Image image = new Image(input);
James_D
  • 201,275
  • 16
  • 291
  • 322