FXML 引用 CSS 个变量

FXML referencing CSS variables

我 google 有一段时间没有回答。在 FXML 中,我知道如何使用 styleClassstyle 标签引用 css、样式等。我想知道是否可以临时引用单个 css 变量。

例如,如果我想设置窗格的填充是否可以实现以下或类似的东西:

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 都会创建一个 class 的新实例,这有点浪费,因为常量本质上是静态的。

以下是我做的:

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>