我正在尝试绑定(bind)两个不同的属性。
我如何绑定(bind)ObjectProperty<LocalDate>
至StringProperty
?
任务类别
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 类
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());
}
}
最佳答案
似乎制作 Task.date
更有意义一个ObjectProperty<LocalDate>
,如果它应该代表一个日期。然后你可以按照通常的方式双向绑定(bind)它们:
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);
}
}
然后当然
datePicker.valueProperty().bindBidirectional(currentTask.dateProperty());
完全按照需要工作。
请注意,因为在评论中您说您正在使用 StringProperty
当您使用 XMLEncoder
整理数据时,在这种情况下完全有可能使用这种方法。请参阅LocalDate serialization error
如果你真的希望它成为 StringProperty
(我应该强调,这样做确实没有意义),您可以使用 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);
}
};
最后:
currentTask.dateProperty().bindBidirectional(datePicker.valueProperty(), converter);
关于java - 如何在 JavaFX 中将 ObjectProperty<LocalDate> 绑定(bind)到 StringProperty?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49697358/