I want to use JavaFX properties for UI binding, but I don't want them in my model classes (see Using javafx.beans properties in model classes). My model classes have getters and setters, and I want to create properties based on those. For example, assuming an instance bean
with methods String getName()
and setName(String name)
, I would write
SimpleStringProperty property = new SimpleStringProperty(bean, "name")
expecting that property.set("Foobar")
would trigger a call to bean.setName
. But this doesn't seem to work. What am I missing?
The
Simple*Property
classes are full, standalone implementations of their correspondingProperty
abstract classes, and do not rely on any other object. So, for example,SimpleStringProperty
contains a (private)String
field itself which holds the current value of the property.The parameters to the constructor you showed:
are:
bean
: the bean to which the property belongs, if anyname
: the name of the propertyThe
bean
can be useful in aChangeListener
'schanged(...)
method as you can retrieve the "owning bean" of the property that changed from the property itself. Thename
can be used similarly (if you have the same listener registered with multiple properties, you can figure out which property changed: though I never use this pattern).So a typical use of a
SimpleStringProperty
as an observable property of an object looks like:The functionality you are looking for: to wrap an existing Java Bean style property in a JavaFX observable property is implemented by classes in the
javafx.beans.property.adapter
package. So, for example, you could doCalling
with this setup will effectively cause a call to
If the bean supports
PropertyChangeListener
s, theJavaBeanStringProperty
will register aPropertyChangeListener
with the bean. Any changes to thename
property of the Java Bean will be translated by theJavaBeanStringProperty
into JavaFX property changes. Consequently, if the underlying JavaBean supportsPropertyChangeListener
s, then changes to the bean viawill result in any
ChangeListener
s (orInvalidationListener
s) registered with theJavaBeanStringProperty
being notified of the change.So, for example, if the Bean class is
Then the following code:
will produce the output:
If the JavaBean does not support
PropertyChangeListener
s, then changes to the bean viabean.setName(...)
will not propagate toChangeListener
s orInvalidationListener
s registered with theJavaBeanStringProperty
.So if the bean is simply
The JavaBeanStringProperty would have no way to observe the change, so the change listener would never be invoked by a call to
bean.setName()
. So the test code above would simply output