Evaluation context

By default, expressions are evaluated against the root element of the FXML document. This can be used to bind properties of controls to custom properties defined in the code-behind class. For other use cases, alternative evaluation contexts can be specified:

Selector Evaluates against
(no notation) root element, or fx:context if set
:context explicit selector for the no-notation default context
:root root element, regardless of fx:context
:element current element
:parent(0) current element, equivalent to :element
:parent or :parent(1) immediate parent of the current element
:parent(N) element N levels above the current element
:parent<MyType> nearest ancestor assignable to MyType
:parent<MyType>(0) current element, provided it is assignable to MyType
:parent<MyType>(N) Nth matching ancestor, where the nearest matching ancestor is 1

Context selectors are specified as part of the expression path:

<Rectangle height="${:element.width}"/>

A context selector is a complete expression primary. For example:

  • :context returns the default evaluation context object
  • :element returns the current element
  • :parent returns the immediate parent element
  • :parent === owner is an identity comparison with another object

The type qualifier and depth can be used independently or together: :parent<Pane> selects the nearest Pane ancestor, while :parent<Pane>(2) selects the second matching Pane ancestor. A depth of 0 always denotes the current element and succeeds for a typed selector only when the current element has the requested type.

Changing the default evaluation context with fx:context

The default evaluation context is the root element of the FXML document. This can be changed with the fx:context attribute, which can be bound to an arbitrary object:

com/sample/MyControl.java
public class MyControl extends MyControlBase {
    final MyBindingContext myContext;

    MyControl() {
        myContext = new MyBindingContext();
        initializeComponent();
    }
}

class MyBindingContext {
    ObjectProperty<User> userProperty();
}
com/sample/MyControl.fxml
<StackPane xmlns="http://javafx.com/javafx" xmlns:fx="http://jfxcore.org/fxml/2.0"
           fx:subclass="com.sample.MyControl"
           fx:context="$myContext">
    <!-- "user.name" will be evaluated against "myContext" -->
    <Label text="${user.name}"/>
</StackPane>

fx:context can be set not only to a specific object, but also be bound to an ObservableValue if the evaluation context is expected to change. Note that this will incur listener management overhead.


This site uses Just the Docs, a documentation theme for Jekyll.