WaffleMan0310 WaffleMan0310 - 1 month ago 13
Java Question

Why use JavaFX properties?

Pardon my question if it may seem stupid but I'm curious. I am making a program in Java of which will have a GUI, and am curious about the whole idea of properties. Why use them when we can just add data to a class? For example:

class myButton extends Button {

private boolean booleanProperty = false;

myButton(args...) {
// Do something with the property
}

public void setProperty(boolean value) {
this.booleanProperty = value;
}

public boolean getProperty() {
return this.booleanProperty;
}
}


Seems to work just fine for storing additional information on the custom implementation of the button. But what about:

class myButton extends Button {

private SimpleBooleanProperty booleanProperty = new SimpleBooleanProperty(false);

myButton(args...) {
// Do something with the property
}

public void setProperty(boolean value) {
this.booleanProperty.set(value);
}

public boolean getProperty() {
return this.booleanProperty.get();
}
}


The only real difference, I am seeing (correct me if I'm wrong) is that that you can attach listeners to the property values, but I feel as if there has to be more than just that. Ideas?

Answer

The power of JavaFX's properties is that they can be bound in ways that will automatically update the UI when a change occurs.

As an example consider an element you want to hide if a textField contains no value:

TextField tf = ...
Node container = ...
container.visibleProperty.bind(tx.textProperty.isNotEmpty());

Now as you change the text in tf, you will see container switching whether its visible based on the presence of text.

Comments