我想将一个 css 文件链接到我的应用程序。 在我的 fxml 文件中,我使用了这个:
<stylesheets>
<URL value="@../stylesheet1.css" />
</stylesheets>
...当我在 scenebuilder 中打开 fxml 文件时,我可以看到样式预览。但是当我尝试运行该应用程序时出现错误:
java.net.MalformedURLException:无协议(protocol):../stylesheet1.css
所以我是这样测试的:
<stylesheets>
<String fx:value="stylesheet1.css" />
</stylesheets>
现在情况正好相反 - 应用程序启动并应用了 css,但我没有在 scenebuilder 中看到预览。错误信息:
“文件 stylesheet1.css 不存在。找不到资源 stylesheet1.css。”
那么如何正确附加 css 文件呢?
好吧,虽然我的问题没有回答为什么它不能按上述方式工作,但我找到了一个适合我的解决方案。在我的 FXML 中,我只有一行
<?scenebuilder-stylesheet ../stylesheet1.css?>
所以 Scenebuilder 使用该 CSS。 在我的主课中,我以编程方式设置样式表:
Scene scene = new Scene(root);
String css = this.getClass().getResource("../stylesheet1.css").toExternalForm();
scene.getStylesheets().add(css);
最佳答案
我发现在 fxml
中包含 css
文件的可用且可行的解决方案
就像堆栈 Pane 一样,将 stylesheets="@app/cssfilename.css"
添加到 fxml
文件的父节点
<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>
关于css - 如何在 FXML 中添加 CSS 样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975897/