Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
968 views
in Technique[技术] by (71.8m points)

javafx - How to add a CSS stylesheet in FXML

I'd like to link a css file to my application. In my fxml file I use this:

  <stylesheets>
    <URL value="@../stylesheet1.css" />
  </stylesheets>

...and I can see a styled preview when I open the fxml file in scenebuilder. But when I try to run the application I get an error:

java.net.MalformedURLException: no protocol: ../stylesheet1.css

So I tested it this way:

<stylesheets>
    <String fx:value="stylesheet1.css" />
</stylesheets>

and now it's other way round - the application starts and applies the css, but I don't see the preview in scenebuilder. The error message:

"The file stylesheet1.css doesn't exist. Resource stylesheet1.css not found."

So how do I attach the css file properly?


Well, although my question wasn't answered why exactly it doesn't work the above way, I found a solution that works for me. In my FXML I have just the line

<?scenebuilder-stylesheet ../stylesheet1.css?>

so Scenebuilder works with that css. And in my main class I set the stylesheet programmatically:

Scene scene = new Scene(root);
String css = this.getClass().getResource("../stylesheet1.css").toExternalForm(); 
scene.getStylesheets().add(css);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What I found usable and working solution to include css file in fxml is add stylesheets="@app/cssfilename.css" to the parent node of the fxml file just as for stack pane

<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="app.fxml.SettingsController" stylesheets="@app/cssfilepath.css">

......
.....
.....
</StackPane>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...