Dynamically add CSS styles to JavaFX

I would like to add a CSS file that is located somewhere in the file system. The goal is to write an application in which the user can add JavaFX CSS files (which are created by anyone and located anywhere) dynamically.
I tried something similar, just for testing, to see if dynamically added CSS files work:

public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Label label = new Label("Hello"); Scene scene = new Scene(label); //file would be set by an file chosser File file = new File("C:/test.css"); scene.getStylesheets().add(file.getAbsolutePath()); primaryStage.setTitle("Title"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 

But I always get the same error:

 WARNING: com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged Resource "C:\test.css" not found. 

How can i fix this?

+6
source share
5 answers

Your problem is that you are not using the URL. Here you can find additional documentation on how CSS loads with a link to CSS.

If you have a URL like String , you can dynamically set CSS with an external file as follows:

 private boolean isANext = true; public void start(Stage primaryStage) throws Exception { Button button = new Button("Change CSS"); VBox vbox = new VBox(10); vbox.setAlignment(Pos.CENTER); vbox.getChildren().add(button); scene = new Scene(vbox, 200, 200); button.setOnAction(ev -> { // Alternate two stylesheets just for this demo. String css = isANext ? "file:///C:/temp/a.css" : "file:///C:/temp/b.css"; isANext = !isANext; System.out.println("Loading CSS at URL " + css); scene.getStylesheets().clear(); scene.getStylesheets().add(css); }); primaryStage.setTitle("Title"); primaryStage.setScene(scene); primaryStage.show(); } 

In a.css

 .button { -fx-text-fill: white; -fx-background-color: red; } 

And in b.css

 .button { -fx-text-fill: white; -fx-background-color: black; } 
+11
source

If css in the same package just use

 scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm()); 
+11
source

You can get the url from java.io.File

 File file = new File("style.css"); URL url = file.toURI().toURL(); scene.getStylesheets().add(url.toExternalForm()); 

or in short form

 scene.getStylesheets().add((new File("style.css")).toURI().toURL().toExternalForm()); 
+4
source

Excluded because the string "C:/test.css" not a URI resource. Therefore, you must convert your string to a URI resource.

With Java 7, you can:

 String uri = Paths.get("C:/test.css").toUri().toString(); scene.getStylesheets().add(uri); 
+1
source
 scene.setUserAgentStylesheet("Assets/StyleSheets/Styless.css"); 
0
source

Source: https://habr.com/ru/post/943708/


All Articles