如何将 ObjectProperty<Date> 转换为 ObjectProperty<LocalDate>
How to convert ObjectProperty<Date> to ObjectProperty<LocalDate>
我要绑定
dp_date_add.valueProperty().bindBidirectional(model.forDateProperty());
其中 forDateProperty()
是:
public ObjectProperty<Date> forDateProperty() {
if(forDate == null){
forDate = new SimpleObjectProperty<>();
}
return forDate;
}
问题是 bindBiderectional
仅接受 LocalDate
。我试过这个:
dp_date_add.valueProperty().bindBidirectional(model.forDateProperty().get().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
但它不起作用,因为它转换为 LocalDate,而不是 属性 LocalDate。
如果可以的话,解决这个问题的简单方法是更改模型,使其使用 ObjectProperty<LocalDate>
。假设你不能那样做,你需要使用两个监听器:
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()));
我要绑定
dp_date_add.valueProperty().bindBidirectional(model.forDateProperty());
其中 forDateProperty()
是:
public ObjectProperty<Date> forDateProperty() {
if(forDate == null){
forDate = new SimpleObjectProperty<>();
}
return forDate;
}
问题是 bindBiderectional
仅接受 LocalDate
。我试过这个:
dp_date_add.valueProperty().bindBidirectional(model.forDateProperty().get().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
但它不起作用,因为它转换为 LocalDate,而不是 属性 LocalDate。
如果可以的话,解决这个问题的简单方法是更改模型,使其使用 ObjectProperty<LocalDate>
。假设你不能那样做,你需要使用两个监听器:
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()));