You're building a JavaFX library with properties that must appear read-only to external clients while remaining updatable to library code. How do you accomplish this duality? This post presents JavaFX 8's answer to this question.
The need for read-only exposure
Before I show you how to create updatable properties that are read-only to external clients, let's review how to define a simple property. Listing 1 presents the source code to a class that implements a counter property.
Listing 1. Implementing a counter property
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
public final class Counter
{
private IntegerProperty counter = new SimpleIntegerProperty();
public IntegerProperty counterProperty()
{
return counter;
}
public int getCounter()
{
return counter.get();
}
public void increment()
{
counter.set(counter.get() + 1);
}
}
Counter first introduces a javafx.beans.property.IntegerProperty field that defines a counter property wrapping a 32-bit integer value. Because IntegerProperty is abstract, I initialize this field to an instance of the concrete javafx.beans.property.SimpleIntegerProperty class, which implements the property. Furthermore, its noargument constructor initializes the property value to 0.