我用谷歌搜索了一下,没有得到答案。在 FXML 中,我知道如何使用 styleClass
和 style
标签引用 css、样式等。我想知道是否可以临时引用单个 css 变量。
例如,如果我想设置 Pane 的填充是否可以实现以下或类似的东西:
example.css
/* ---------- Constants ---------- */
*{
margin_small: 1.0em;
margin_large: 2.0em;
}
示例 fxml
<padding>
<Insets bottom="margin_small" left="margin_small" right="margin_small" top="margin_large" />
</padding>
另一种方法是为这些样式的每个组合创建一个 css 样式,或者使用 style
标记引用它们。我宁愿避免这两种选择。
这可能吗?
最佳答案
我无法得到我真正想要的解决方案,我希望能够包含一个文件(fxml、css、值等)并直接引用。我能做的最好的事情是为每个常量创建一个带有属性的 POJO,然后在 fxml 中定义 POJO 的一个实例。
问题是每个 fxml 都会创建一个类的新实例,这有点浪费,因为常量本质上是静态的。
下面是我做的:
FXMLConstants.java
// Class instance containing global variables to be referenced in fxml files. This is to allow us to use constants similarly to how Android's xml structure does
public class FXMLConstants
{
private static final DoubleProperty marginSmall = new SimpleDoubleProperty(10);
private static final DoubleProperty marginMedium = new SimpleDoubleProperty(15);
private static final DoubleProperty marginLarge = new SimpleDoubleProperty(25);
public Double getMarginSmall()
{
return marginSmall.getValue();
}
public Double getMarginMedium()
{
return marginMedium.getValue();
}
public Double getMarginLarge()
{
return marginLarge.getValue();
}
}
Example.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import com.example.FXMLConstants?>
<GridPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<FXMLConstants fx:id="fxmlConsts" />
</fx:define>
<padding>
<Insets bottom="$fxmlConsts.marginMedium" left="$fxmlConsts.marginLarge" right="$fxmlConsts.marginLarge" top="$fxmlConsts.marginMedium" />
</padding>
<children>
<Label text="Test" GridPane.columnIndex="0" GridPane.rowIndex="0" />
</children>
</GridPane>
关于css - FXML 引用 CSS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30026349/