FXML引用CSS变量

时间:2015-05-04 09:07:00

标签: css javafx fxml

我有一点点没有答案的谷歌。在FXML中,我知道如何使用styleClassstyle标记引用css,样式等。我想知道是否可以引用单个css变量adhoc。

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

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标记引用它们。我更愿意避免这两种选择。

这可能吗?

1 个答案:

答案 0 :(得分:0)

我无法达到我真正想要的解决方案,我希望能够直接包含文件(fxml,css,values等)和引用。我能做的最好的事情是创建一个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>