My application contains several different packages that I want to be able to access CSS theme files, stored in the application's themes
folder.
After following several tutorials and other StackExchange questions and answers, I haven't found anything that works for my situation. In fact, many of the "answers" just say to move the .CSS files into the same folder as the class calling for it; that is not an acceptable solution for my situation.
My directory structure is similar to this:
- Root Project Folder
- /data
- /themes
- /Theme.css
- /src
- sample
- /Main.java
- /Controller.java
- /sample.fxml
How would I apply the Theme.css
to my sample.fxml
file?
I threw together a sample project that works to illustrate my issue.
Main.java:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
Scene scene = new Scene(root, 300, 275);
scene.getStylesheets().add(
getClass().getResource("/themes/Theme.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
sample.fxml:
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
</GridPane>
The Error:
Caused by: java.lang.NullPointerException
at sample.Main.start(Main.java:18)
Also Tried:
scene.getStylesheets().add("file:///themes/Theme.css");
scene.getStylesheets().add("file:///../themes/Theme.css");
Those both present the same "resource not found" error.
This code works in the Sample above:
File css = new File("themes/Theme.css");
scene.getStylesheets().add("file:///" + css.getAbsolutePath());
However, I cannot get the exact same code to work within my larger project with the same structure.
I get this error:
WARNING: Resource "file:////[PATH TO PROJECT]/themes/Theme.css" not found
The full path shown in the error is exactly correct and leads to the file that DOES exist.
How would I go about troubleshooting this? Since it works fine in the sample project but not my larger one, the problem obviously lies somewhere in my other project code.
But why would the compiler tell me a file doesn't exist when it clearly does?
Incidentally, my goal here is to allow users to select a "Theme" to use to style the entire application. The /themes
folder contains several dozen themes to choose from.
Thank you in advance for all your help!