如何在FXML中添加CSS样式表 [英] How to add a CSS stylesheet in FXML
问题描述
我想将css文件链接到我的应用程序。
在我的fxml文件中我使用这个:
< stylesheets&
< URL value =@ .. / stylesheet1.css/>
< / stylesheets>
...当我在scenebuilder中打开fxml文件时,我可以看到一个样式化的预览。但是当我尝试运行应用程序时,我得到一个错误:
java.net.MalformedURLException:no protocol:../ stylesheet1.css
所以我这样测试:
< stylesheets&
< String fx:value =stylesheet1.css/>
< / stylesheets>
现在它的另一种方式 - 应用程序启动并应用css,但我没有看到在scenebuilder中的预览。错误讯息:
文件stylesheet1.css不存在,找不到资源stylesheet1.css b
$ b
那么如何正确附加css文件呢?
问题没有回答为什么它不工作的上述方式,我发现一个解决方案,为我工作。在我的FXML我只有行
<?scenebuilder-stylesheet ../stylesheet1.css?>
所以Scenebuilder使用css。
在我的主类中,我以编程方式设置样式表:
Scene scene = new Scene
String css = this.getClass()。getResource(../ stylesheet1.css)。toExternalForm();
scene.getStylesheets()。add(css);
我发现有用和有效的解决方案包括<$ fxml
中的 stylesheets =@ app / cssfilename.css
fxml
文件的父节点
< StackPane maxHeight = - InfinitymaxWidth = - InfinityminHeight = - InfinityminWidth = - InfinityprefHeight =400.0prefWidth =600.0xmlns =http: /javafx.com/javafx/8xmlns:fx =http://javafx.com/fxml/1fx:controller =app.fxml.SettingsControllerstylesheets =@ app / cssfilepath.css>
......
.....
.....
< / StackPane>
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);
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>
这篇关于如何在FXML中添加CSS样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!