javafx - Why relative path doesn't work in JAVA in JAR-file? -
this question has answer here:
- javafx: location not set error 1 answer
i have simple javafx project. consists from:
- src/app/main.java
- src/app/controller/maincontroller.java
- src/app/controller/secondarywindowcontroller.java
- src/app/view/main.fxml
- src/app/view/secondarywindow.fxml
the controller maincontroller.java has method (handler of press button):
public void openwindow(actionevent event) { pane root = null; try { system.out.println("url: " + getclass().getresource("../view/secondarywindow.fxml")); fxmlloader loader = new fxmlloader(getclass().getresource("../view/secondarywindow.fxml") ); root = loader.load(); } catch(exception e) { e.getmessage(); e.printstacktrace(); } if (root != null) { scene scene = new scene(root,400,100); stage secstage = new stage(); secstage.settitle("secondary window"); secstage.setscene(scene); secstage.show(); } } code getclass().getresource("../view/secondarywindow.fxml") return right url if run project compile files. return null if run project jar-file.
i compile files using:
javac -d bin src\app\main.java javac -d bin src\app\controller\*.java xcopy src\app\view\*.fxml bin\app\view /s /e /d /y and run compile files using:
java -classpath bin app.main catalog bin has similar structure of files:
- bin/app/main.class
- bin/app/controller/maincontroller.class
- bin/app/controller/secondarywindowcontroller.class
- bin/app/view/main.fxml
- bin/app/view/secondarywindow.fxml
and create jar-file using:
jar cvfm simplefxmlapp.jar manifest.mf -c bin app manifest.mf
manifest-version: 1.0 created-by: denys selivanov main-class: app.main why relative path doesn't work in jar-file , getclass().getresource("../view/secondarywindow.fxml") return null ? how repair that?
one of problem's solves keep controllers , views files in 1 catalog , use relative path "secondarywindows.fxml", want keep structure files of project.
and can download project here. link access 30 days.
i see vote close says it's duplicate of this q&a, don't think explains specifics of .., here go:
.. works on resources on filesystem, because .. actual entry on filesystem, points parent directory. not exist within jars, won't work point "parent package" when classes & resources packaged in jar.
solution: if can accept dependency controller class main class, can instead:
main.class.getresource("view/secondarywindow.fxml") in case you'll need either reference class high enough in packages hierarchy, or use absolute path root package (getclass().getclassloader().getresource("app/view/secondarywindow.fxml") in case apparently).
Comments
Post a Comment