(Following this question, this is what prompted it)
I have a model class with a LongProperty
:
public class Model {
private final SimpleLongProperty number = new SimpleLongProperty(this, "number");
public long getNumber() { return number.get(); }
public void setNumber(long number) { this.number.set(number); }
public LongProperty numberProperty() { return number; }
}
Now, in my controller I have a TableColumn<Model, Long> colNumber
which I want to bind to this property. I know I can use PropertyValueFactory
, but I don't like the idea of giving the property by name when I can pass it programmatically, and have the compiler/ide spell-check me. Basically I want to do something like this (I actually want to make it more concise, example in the end):
colNumber.setCellValueFactory( cdf -> cdf.getValue().numberProperty() );
but this gives me a compilation error:
java: incompatible types: bad return type in lambda expression javafx.beans.property.ObjectProperty cannot be converted to javafx.beans.value.ObservableValue
As I said, I know I can use PropertyValueFactory
, and also have static final strings for the property names, but I find it less elegant. Is there a way to make this programmatic approach work? Some casting-magic?
Appendix:
The actual way I wanted to make it is with a helper method:
private <S,T> Callback<CellDataFeatures<S,T>, ObservableValue<T>> propertyFactory(Callback<S, ObservableValue<T>> callback) {
return cdf-> callback.call(cdf.getValue());
}
and then I can just use
colNumber.setCellValueFactory(propertyFactory(Model::numberProperty));
which keeps my code very concise and readable, and has the compiler checking me for typos etc.