title: JavaFX binding and null values
body: <p>I was wondering how to bind values where the source of the bind could be null.</p>
  
  <p>I have a property:</p>
  
  <pre><code>private ObjectProperty&lt;Operation&gt; operation = new SimpleObjectProperty&lt;&gt;(null);
  </code></pre>
  
  <p>I also have a text field:</p>
  
  <pre><code>@FXML
  private Text txtCurrentOperation;
  </code></pre>
  
  <p>I would like to bind the <code>textProperty</code> of the field to the value of the operation object.</p>
  
  <p>My first thought was to use FluentAPI with its when/then/otherwise construct, but it is eagerly evaluated so the solution:</p>
  
  <pre><code>Bindings.when(operation.isNotNull())
      .then("null")
      .otherwise(operation.get().getName()));
  </code></pre>
  
  <p>will throw a NPE, because the parameter of <code>otherwise</code> is evaluated no matter what the result of the <code>when</code>.</p>
  
  <p>My next idea was to use lambda somehow:</p>
  
  <pre><code>txtCurrentOperation.textProperty().bind(() -&gt;
          new SimpleStringProperty(
               operation.isNotNull().get() ? "Null" : operation.get().getName()
              ));
  </code></pre>
  
  <p>But the bind has no lambda enabled solution. (Later I realized that it couldn't have, becasue the real work goes backward: the change of the binded object (operation) will trigger the update of the binder (the field text property).)</p>
  
  <p>Some articles I found suggested to use an "extremal" value for the property instead of null. But Operation is a complex and heavy weight component so it is not trivial to construct an artifical instance to represent null. Even more, this seems to me boilercode, something the binding mechanism is designed to help eliminating.</p>
  
  <p>My next try was to logically swap the binding direction and add listener to the operation property and let it update the field programatically. It works and rather simple as long as the need of update only depends the operation object instances:</p>
  
  <pre><code> operation.addListener((e) -&gt; {
          txtCurrentOperation.setText(operation.isNull().get() ? 
              "Null" : operation.get().getName());
   });
   operation.set(oper);
  </code></pre>
  
  <p>It is relatively simple, but doesn't work: it throws "A bound value cannot be set." exception and I don't see why is the text property of the control regarded as bound.</p>
  
  <p>I ran out of ideas. After much searching, I still cannot solve the simple problem to update a text field differently based on whether the source is null or not.</p>
  
  <p>This seems so simple and everyday problem, that I am sure I missed the solution.</p>