2015-05-04 29 views
0

我已经谷歌有点没有答案。在FXML中,我知道如何使用styleClassstyle标签来引用CSS,样式等。我想知道是否可以引用单个css变量adhoc。FXML引用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标记引用它们。我宁愿避免这两种选择。

这可能吗?

+0

你不能做你正在尝试样品中做代码在你的问题。也许这里的信息将有所帮助:[在FXML中通过表达式绑定使用em单元](http://stackoverflow.com/a/23706030/1155209),但我不确定,因为你没有[解释你尝试的问题是什么解决是](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – jewelsea

+0

感谢您的回复。没有一个具体的问题,我只是想利用一个全局变量来处理边界等事情。由于fxml负责布局,将这些常量或逻辑放在控制器中会很麻烦。我基本上想要做的是在android的xml中可以引用值文件。但在javafx中,它将是css而不是值 – Kevin

+0

最后决定为每个我想参考的常量创建一个带有属性的POJO。然后在每个FXML文件中定义一个POJO的实例并以这种方式引用它们。没有我想要的那么整齐,但仍然比在每个控制器中都好。并且比硬编码更好 – Kevin

回答

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>