11. Building Reactive Systems with JavaFX
Today's tips is to take the leap from Swing to JavaFX, the latter being much more modern and feature full than the former.
Properties and ObservabilityProperty objects are important when designing JavaFX applications. Almost everything in the FX library can be observed such as the text content of a field, the position of a slider or the status of a checkbox. Properties can be Writable and Readable. A writable value can be updated using its setter or by user interaction with the component whereas a readable can react (via notifications) to external events.
// Both readable and writable StringProperty name = new SimpleStringProperty("Schema Name"); // Only readable ObservableBooleanValue nameIsEmpty = name.isEmpty();
So, the variable nameIsEmpty can return true if the name is currently empty or false if name is non-empty.
BindingsNow that we have writable and readable values, we can define custom rules how they all relate to each other (e.g. we can "wire up" our model). Bindings are either unidirectional or bidirectional. Unsurprisingly, bidirectional bindings requires that both properties are writable.
Here is an example of binding:
TextField firstField = new TextField("first"); TextField secondField = new TextField("second"); firstField.prefWidthProperty().bind(secondField.widthProperty());
This will hint JavaFX that we want our firstTextField to have the same width that the secondField. This relation will be maintained over time so if we change the secondField's width, then the firstField's hinted width is updated automatically.