Yesterday my JavaFX-maven project was working fine in InteliJ IDE, but packed JRE with maven javaFX:jlink command was throwing similar exeption to this one I`ve got today with javaFX:run command:
Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
at javafx.graphics/javafx.scene.image.Image.validateUrl(Image.java:1125)
at javafx.graphics/javafx.scene.image.Image.<init>(Image.java:618)
at javafx.graphics/javafx.scene.image.ImageView.<init>(ImageView.java:194)
at org.example/org.example.GameMenu.construct(GameMenu.java:20)
at org.example/org.example.App.start(App.java:23)
The code that throws exeption:
public class GameMenu {
static int picOfChoice = (int) (Math.random() * 6);
public static Font font = Font.loadFont(Objects.requireNonNull(GameMenu.class.getResource("/utility/pixRectv2.ttf")).toExternalForm(), 48);
public static Font font2 = Font.loadFont(Objects.requireNonNull(GameMenu.class.getResource("/utility/pixRectv2.ttf")).toExternalForm(), 32);
public static Group menu = new Group();
public static Group construct() {
menu = new Group();
ImageView logo = new ImageView("menu/logo3.png");
Image backg3 = new Image("backg/backgPL" + picOfChoice + ".png", winWidth, winHeight, false, false);
ImageView backgV3 = new ImageView(backg3);
menu.getChildren().add(backgV3);
logo.setX(0);
logo.setY(0);
menu.getChildren().add(logo);//Logo is on top
return menu;
}}
No code on that line was changed. Resources folder was not moved. pom.xml wasnt changed. Those png`s are accesible for R/W and even recognized by IDE as images
I have tried different path formatting (absolute path included) and it did not help. But ImageView logo = new ImageView("file:menu/logo3.png"); loads no image, while not throwing any exeption.
I have tried opening my other javaFX projects and they all work, while using similar project structure and similar way of useing new ImageView(). I have created new project with javaFX and it loads images just fine, so I wasnt able to recreate this problem.
I have opened this project on other machines, it throws same exeptions. Fonts of javaFX in code above still load fine. Similar way of loading images ( through GameMenu.class.getResource ) works too.
The question: How to fix it and how to avoid it in future?
UPD: Thanks to @James_D and @Dmitriy Popov for answers;
I have added new method for path extraction via widely used .class.getResource()
So fixed code looks like
ImageView logo = new ImageView(Utility.getImageRes("/menu/logo3.png"));
Where Utility.getImageRes(String) is
public static String getImageRes(String path) {
return Objects.requireNonNull(Utility.class.getResource(path)).toExternalForm();
}
It works now, both with javaFX:run and jlink commands. Reason why previous method stopped working is still unknown.