rakamakafo
rakamakafo

Reputation: 1154

How to convert ObjectProperty<Date> to ObjectProperty<LocalDate>

I want to bind

dp_date_add.valueProperty().bindBidirectional(model.forDateProperty());

where forDateProperty() is:

public ObjectProperty<Date> forDateProperty() {
        if(forDate == null){
            forDate = new SimpleObjectProperty<>();
        }
        return forDate;
    }

The problem is bindBiderectional accpets only LocalDate. I've tried this:

dp_date_add.valueProperty().bindBidirectional(model.forDateProperty().get().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());

But it doesn't works, because it convert to LocalDate, not to Property LocalDate.

Upvotes: 1

Views: 752

Answers (1)

James_D
James_D

Reputation: 209418

The easy way to fix this, if you can, is to change the model so it uses an ObjectProperty<LocalDate>. Assuming you can't do that, you need to use two listeners:

dp_date_add.valueProperty().addListener((obs, oldDate, newDate) -> 
    model.forDateProperty().set(Date.from(newDate.atStartOfDay(ZoneId.systemDefault()).toInstant())));

model.forDateProperty().addListener((obs, oldDate, newDate) -> 
    dp_date_add.setValue(model.forDateProperty().get().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()));

Upvotes: 2

Related Questions