Creating custom bindings
If you have a complex logic, you can create your own binding by either extending the corresponding abstract base class—DoubleBinding, StringBinding, ObjectBinding—there are several options for different types; or by using a utility method from the Bindings class.
Implementing base binding classes
The concept of binding is simple:
- Add a listener to change events you want to track
- Compute the value you want to have
Correspondingly, in the following example, we call bind() for the desired property and override computeValue() method:
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Click me");
StackPane root = new StackPane();
root.setBackground(Background.EMPTY);
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
ObjectBinding<Paint> objectBinding = new ObjectBinding<Paint>() {
{
bind(btn.pressedProperty());
}
...