如何在 FXML 中添加 CSS 样式表 [英] How to add a CSS stylesheet in FXML

查看:40
本文介绍了如何在 FXML 中添加 CSS 样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个 css 文件链接到我的应用程序.在我的 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>

...当我在场景构建器中打开 fxml 文件时,我可以看到样式预览.但是当我尝试运行该应用程序时出现错误:

...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:无协议:../stylesheet1.css

所以我是这样测试的:

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

现在情况正好相反 - 应用程序启动并应用 css,但我在 Scenebuilder 中看不到预览.错误信息:

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:

文件 stylesheet1.css 不存在.找不到资源 stylesheet1.css."

那么如何正确附加css文件?

So how do I attach the css file properly?

好吧,虽然我的问题没有得到解答,为什么它不能以上述方式工作,但我找到了一个适合我的解决方案.在我的 FXML 中,我只有一行

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?>

所以 Scenebuilder 使用该 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);

推荐答案

我发现在 fxml 中包含 css 文件的可用且有效的解决方案是将 stylesheets="@app/cssfilename.css" 添加到 fxml 文件的父节点,就像堆栈窗格

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆