Issue
I have node
property that is ObjectProperty<VBox>
and I want to have nodeSize
property that depends on node
property.
It will look like this:
public final class PropertyProblem {
public PropertyProblem() {
nodeSize.bind(initNodeSizeBinding(node));
}
private ObjectBinding<Dimension2D> initNodeSizeBinding(ObjectProperty<VBox> nodeProperty) {
return Bindings.createObjectBinding(() -> {
if (nodeProperty.get() == null) {
return null;
}
VBox node = nodeProperty.get();
ReadOnlyDoubleProperty widthProperty = node.widthProperty(),
heightProperty = node.heightProperty();
return new Dimension2D(widthProperty.get(), heightProperty.get());
}, nodeProperty);
}
// node property
private final ObjectProperty<VBox> node = new SimpleObjectProperty<>(this, "node", null);
public ObjectProperty<VBox> nodeProperty() {
return node;
}
public void setNode(VBox val) {
node.set(val);
}
public VBox getNode() {
return node.get();
}
// nodeSize property
private final ReadOnlyObjectWrapper<Dimension2D> nodeSize = new ReadOnlyObjectWrapper<>
(this, "nodeSize");
public ReadOnlyObjectProperty<Dimension2D> nodeSizeProperty() {
return nodeSize;
}
public Dimension2D getNodeSize() {
return nodeSize.get();
}
}
Let's focus on initNodeSizeBinding()
method.
The problem is I can't provide dependencies (node's width and height) for the binding, because obviously node
property can be null
. Is there any other way to cope with this without creation of binding every time the node
property changes its value?
Solution
I think you want Bindings.when, which is the dynamic binding equivalent of the tertiary operator (that is, condition ?
trueExpr :
falseExpr):
return Bindings
.when(nodeProperty.isNotNull())
.then(Bindings.createObjectBinding(
() -> new Dimension2D(nodeProperty.get().getWidth(),
nodeProperty.get().getHeight()),
Bindings.selectDouble(nodeProperty, "width"),
Bindings.selectDouble(nodeProperty, "height"))
.otherwise((Dimension2D) null);
Answered By - VGR
Answer Checked By - Timothy Miller (JavaFixing Admin)