0

I have a pretty specific problem. Recently I'm trying to learn JavaFX and everything works for me, but I can not load files. When I tried the classic basic code to create a stage, scene and use an image there:

public void start(Stage primaryStage) throws Exception {
        // Load the image file
        Group root = new Group();
        Scene scene = new Scene(root,500,500);

        Image img = new Image("img.png");
        ImageView imgV = new ImageView(img);

        root.getChildren().add(imgV);


        primaryStage.setScene(scene);
        primaryStage.show();
} 

It kept crashing and I kept getting these two errors:

Caused by: java.lang.RuntimeException: Exception in Application start method
Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found

The "img.png" file is in the same folder as the Main class.

I got a little further with this and found elsewhere that the file path has to be written like this on MacOS:

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

for it to be a valid URL, this throws no errors and opens the window but does not show the image. When I use absolute URL of the image file, the image is being shown.

My question therefore is - how should i write it so that the image will be shown and I will use relative path to the file? I really need it also because I will need to include mulitple files (like FXML) in my work later. Thanks :)

I expect to find a solution that will allow me to use a relative path instead of the absolute one.

Adam
  • 3
  • 1
  • 1
    Keep in mind the file reference there will be relative to your _execution directory_ (not the code directory!). Per documentation of `File`: "By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.". You likely want something like `Class#getResource`, where you'd export your resources with a program jar/war/etc – Rogue Mar 19 '23 at 18:34

0 Answers0