7

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 multiplied by 2 (i.e. 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 controller (which I would like to avoid)?

Abra
  • 19,142
  • 7
  • 29
  • 41
Radosław Łazarz
  • 950
  • 1
  • 11
  • 25

2 Answers2

4

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:

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.

Community
  • 1
  • 1
jewelsea
  • 150,031
  • 14
  • 366
  • 406
4

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}" />
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Is it working every time, or only when a binding is possible? I wanted to define coordinates for Polygon that way `` and got an exception. – Radosław Łazarz Mar 26 '15 at 17:56
  • @RadosławŁazarz What exception is it? – Eng.Fouad Mar 26 '15 at 18:02
  • A `java.lang.NumberFormatException: For input string: "$width"`. On the other hand it works perfectly for ``, so it is a problem with `Double` mostly. And it is the Polygon shape I hoped to define in smart way... – Radosław Łazarz Mar 26 '15 at 18:07