Since I changed the structure of my Java source packages, some of the file open functions don't want to work anymore. I moved some resources (icon, properties files, etc) from MyProject\res\
to MyProject\src\res\
.
I think I should use this.getClass().getResourceAsStream("icon.png")
instead of file path string but I'm not sure.
Here is how I access to the icon file before I change the resources location:
private final static String iconSourcePath = "file:res/icon/icon.png";
primaryStage.getIcons().add(new Image(iconSourcePath));
Is there a rule for access to files in Java? If the requested file is in the source file or outside?
Edit: This is the solution I found.
I found the easiest way is to put allways absolute paths, relative to the src
folder.
For example, in my project I have this folder hierarchy:
src
META-INF
MANIFEST.MF
res
icon
icon.png
lang
MessageBundle
MessageBundle_en.properties
MessageBundle_fr.properties
pref
AppProperties
Properties.properties
simulation
log
Console.java
views
settingsWindows
settingsWindows.fxml
SettingsWindows_Controller.java
simulation
simulation.fxml
Simulation_Controller.java
toolBar
toolBar.fxml
ToolBar_Controller.java
Simulation.java
Main.java
If I need add the icon.png
in the SettingsWindows_Controller.java
(in JavaFX), I will do this like that:
private final static String iconSourcePath = "/res/icon/icon.png";
stage.getIcons().add(new Image(iconSourcePath));
And if I want to load the toolBar.fxml
in any file, I will do that:
private final static String fxmlSourcePathToolBar = "/simulation/views/toolBar/toolBar.fxml";
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(fxmlSourcePathToolBar));
With this methode, it will works in debug mode (in the IDE) AND in the JAR file.