Binding a Label's text property (in an FXML file) to an IntegerProperty (in a controller)

守給你的承諾、 提交于 2019-11-27 14:44:17

You need to add a JavaFX specific accessor variableNameProperty to the controller:

public IntegerProperty counterProperty() {
    return counter;
}

EDIT: More details.
The API documentation mentions not so much about this JavaFX's JavaBeans architecture. Just an introduction about it here (Using JavaFX Properties and Binding) but again nothing about its necessity.

So lets dig some source code! :)
Straightforwardly, we start to look into FXMLLoader code first. We notice prefix for binding expression as

public static final String BINDING_EXPRESSION_PREFIX = "${";

Further at line 279 FXMLLoader determines if (isBindingExpression(value)) then to create binding, instantiates BeanAdapter and gets propertyModel:

BeanAdapter targetAdapter = new BeanAdapter(this.value);
ObservableValue<Object> propertyModel = targetAdapter.getPropertyModel(attribute.name);

If we look into BeanAdapter#getPropertyModel(),

public <T> ObservableValue<T> getPropertyModel(String key) {
    if (key == null) {
        throw new NullPointerException();
    }
    return (ObservableValue<T>)get(key + BeanAdapter.PROPERTY_SUFFIX);
}

it delegates to BeanAdapter#get() after appending String PROPERTY_SUFFIX = "Property";
In the get() method, simply the getter (either counterProperty or getCounter or isCounter) invoked by reflection, returning the result back. If the getter does not exist null returned back. In other words, if the "counterProperty()" does not exist in JavaBean, null returned back in our case. In this case the binding is not performed due to the statement if (propertyModel instanceof Property<?>) in FXMLLoader. As a result, no "counterProperty()" method no bindings.

What happens if the getter is not defined in the bean? Again from the BeanAdapter#get() code we can say that if the "getCounter()" cannot be found the null returned back and the caller just ignores it as no-op imo.

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