Today's tip is to take the leap from Swing to JavaFX, the latter being much more modern and feature-full than the former.
The open-source Speedment UI tool is built using JavaFX, allowing the tool to be more reactive. If we change something in a text box, for example, that property can affect other components directly and dynamically. Getting more specific, if we change the name of a schema, then a tree component showing the entire database structure is updated in real time — and perhaps also a connection URL that depends on the schema name. Here is the complete UI tool code written using JavaFX.
Properties and Observability
Property 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.
Here is how it looks like:
// 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 the name is not empty.
Now that we have writable and readable values, we can define custom rules based on how they all relate to each other (e.g. we can "wire up" our model). Bindings are either unidirectional or bidirectional. Unsurprisingly, bidirectional bindings require 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.
Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.