Reputation: 761
I'm trying to bind between two different properties.
How can i bind ObjectProperty<LocalDate>
to StringProperty
?
Task Class
public class Task {
StringProperty time = new SimpleStringProperty();
ObjectProperty<String> testCase = new SimpleObjectProperty<>();
StringProperty date = new SimpleStringProperty();
public Task(String date, String time, String testCase) {
this.date.set(date);
this.time.set(time);
this.testCase.set(testCase);
}
public String getdate() {
return date.get();
}
public void setDate(String date) {
this.date.set(date);
}
public StringProperty dateProperty() {
return date;
}
}
Controller Class
public class Controller implements Initializable {
@FXML
private DatePicker datePicker;
private Task currentTask = new Task();
@Override
public void initialize(URL location, ResourceBundle resources) {
datePicker.valueProperty().bindBidirectional(currentTask.dateProperty());
}
}
Upvotes: 0
Views: 3085
Reputation: 209418
It seems like it would make more sense to make Task.date
an ObjectProperty<LocalDate>
, if it is supposed to represent a date. Then you can just bind them bidirectionally in the usual way:
public class Task {
private ObjectProperty<LocalDate> date = new SimpleObjectProperty<>();
// ...
public ObjectProperty<LocalDate> dateProperty() {
return date ;
}
public final LocalDate getDate() {
return dateProperty().get();
}
public final void setDate(LocalDate date) {
dateProperty().set(date);
}
}
and then of course
datePicker.valueProperty().bindBidirectional(currentTask.dateProperty());
works exactly as needed.
Note that, since in the comments you say you are using a StringProperty
as you are marshaling the data with an XMLEncoder
, it is perfectly possible to use this approach in that context. See LocalDate serialization error
If you really want this to be a StringProperty
(and I should emphasize, it really doesn't make sense to do it this way), you can use a StringConverter
:
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE ;
StringConverter<LocalDate> converter = new StringConverter<LocalDate>() {
@Override
public LocalDate fromString(String string) {
return string == null || string.isEmpty() ? null : LocalDate.parse(string, formattter);
}
@Override
public String toString(LocalDate date) {
return date == null ? null : formatter.format(date);
}
};
And finally:
currentTask.dateProperty().bindBidirectional(datePicker.valueProperty(), converter);
Upvotes: 2