Search code examples
javajavafxpathrelative-pathtetris

Relative path does not work


I'm trying to reconstruct Tetris in JavaFX. My project is called TetrisProject (C:\Users\Matthias\IdeaProjects\OOPROG\TetrisProject)

Inside Main there is a problem with getting resources. (C:\Users\Matthias\IdeaProjects\OOPROG\TetrisProject\tetris\src\be\kdg\tetris\Main.java)

public class Main extends Application {
    primaryStage.getIcons().add(new Image("tetris\\resources\\images\\icon.png")
}

icon.png is the icon I want to set for my windows. (C:\Users\Matthias\IdeaProjects\OOPROG\TetrisProject\tetris\resources\images\icon.png)

tetris\\resources\\images\\icon.png should be the relative path since

File f = new File(".");
System.out.println(f.getAbsolutePath());

run inside Main.java outputs C:\Users\Matthias\IdeaProjects\OOPROG\TetrisProject\.

The relative path I wrote for icon.png is correct, right?


Solution

  • The path is not a file path, it's a URL for the resource.

    The documentation says "If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case." Presumably resources is a source folder, so the path would need to be simply images/icon.png:

    primaryStage.getIcons().add(new Image("images/icon.png"));
    

    You can check by looking at what is in the output/build/bin folder (whatever your IDE calls it). Depending on how your IDE is configured to handle the resources directory, the image should be copied there, and that is where the Image constructor will be looking at runtime. (Your source folders, obviously, at generally not accessible at runtime.)