JDK 11, JavaFX 15.
Despite the wonderful answer How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application? this is still stymieing me. It does not address loading related resources.
I have a simple example loading an FXML file that refers to a CSS file.
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0"
styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/11.0.1">
<stylesheets>
<URL value="@/styles/root.css" />
</stylesheets>
</AnchorPane>
And this is the pkg/App.java class:
package pkg;
public class App extends Application {
private static Scene scene;
@Override
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(App.class.getResource("root.fxml"));
scene = new Scene(loader.load());
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
This is the root.css
file:
.mainFxmlClass {
}
Here is the jar layout (eliminating maven boiler plate, module info, manifest).
pkg/App.class
pkg/root.fxml
pkg/styles/root.css
styles/root.css
The relevant exception I get is:
Caused by: javafx.fxml.LoadException: Invalid resource: /styles/root.css not found on the classpath
According to Introduction to FXML, under Location Resolution, it says:
As strings, XML attributes cannot natively represent typed location information such as a URL. However, it is often necessary to specify such locations in markup; for example, the source of an image resource. The location resolution operator (represented by an "@" prefix to the attribute value) is used to specify that an attribute value should be treated as a location relative to the current file rather than a simple string.
The exception specifies "/styles/root.css", which is an absolute path. As seen from the JAR layout, I have a /styles/root.css
. But the documentation says "relative to the current file".
Assuming the "current file" is /pkg/root.fxml
, then /pkg/styles/root.css
is (should be) relative to /pkg/root.fxml
(or is it /pkg/App.class?), yet it can not locate this one either.
If I comment out the stylesheets
element, the file loads just fine.
So, where should I place the root.css
file?