1

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?

Zoe
  • 27,060
  • 21
  • 118
  • 148
m4t5k4
  • 55
  • 9

1 Answers1

2

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.)

James_D
  • 201,275
  • 16
  • 291
  • 322
  • It works! Thank you so much, I did not know path worked this way. – m4t5k4 Feb 22 '17 at 15:25
  • 1
    It's in the documentation. You should know what the documentation says. – Lew Bloch Feb 22 '17 at 15:43
  • @LewBloch I only saw an example of how to use Image at school in which case the image was in the same directory as the java class. Our teacher didn't even explain that Image gets the resource via URL nor classpath. You're acting like I'm obligated to read the documentation of everything in Java. – m4t5k4 Feb 23 '17 at 09:47
  • 1
    @m4t5k4 If something is not working, the first thing you should do is read the documentation for the relevant classes and methods. (Really you should read it before you start to use it.) No course is going to teach you everything you need. Reading the relevant docs is the minimum amount of research you should do before posting here. – James_D Feb 23 '17 at 11:42
  • Believe it or not, the documentation often has the answers. Reading the documentation is not a bad thing, and neither is recommending it. If you're averse to documentation it will greatly hamper your progress. – Lew Bloch Feb 23 '17 at 14:57