Is it possible to use arithmetic expression in FXML?

最后都变了- 提交于 2019-12-23 16:27:19

问题


I hoped for a feature that would allow me to work with numbers inside the FXML. For example, tried to define the height of one element to be equal to a constant and the height of the second element to be equal to the same constant*2. Is it possible to do it in FXML at all or do I need to do this part of view build-up inside the controler (which I would like to avoid)?


回答1:


Yes, it is possible:

<?import java.lang.Double?>

...

<fx:define>
    <Double fx:id="xHeight" fx:value="100" />
</fx:define>

...

<Label fx:id="lblElementOne" prefHeight="$xHeight" />
<Label fx:id="lblElementTwo" prefHeight="${xHeight * 2}" />



回答2:


Use an Expression Binding

You can use an expression binding.

<TextField fx:id="textField" prefWidth="40"/>
<Label prefWidth="${textField.prefWidth * 2}"/>

On Constant Definition in FXML

You could access a constant defined in FXML or an FXML definition.

There is an example of the use of such an approach in the answer to:

  • Bind Font Size in JavaFX?

See the section in that answer titled: "Using em units in FXML via expression binding".

On Constant Definition in CSS

BTW, is it possible to define constants in CSS? I thought the OP meant a constant inside FXML, but mentioned CSS.

I assumed a constant in FXML too until I re-read the question where it says "defined i.e. inside a CSS". And, yes you can't really define a constant in JavaFX CSS, the closest thing might be a looked-up-color, but that is pretty specific and a little different. If you pass the CSS through a pre-processor like LESS or SASS, those systems allow the definition of constants (which LESS confusingly calls variables :-). However, you can't directly access that kind of information through FXML.



来源:https://stackoverflow.com/questions/29284004/is-it-possible-to-use-arithmetic-expression-in-fxml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!