【问题标题】:How to bind ObjectProperty<LocalDate> to StringProperty in JavaFX?如何在 JavaFX 中将 ObjectProperty<LocalDate> 绑定到 StringProperty?
【发布时间】:2018-04-06 16:34:08
【问题描述】:

我正在尝试在两个不同的属性之间进行绑定。 如何将ObjectProperty&lt;LocalDate&gt; 绑定到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;
    }
    }

控制器类

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 中创建dateObjectProperty&lt;LocalDate&gt; 不是更有意义吗?
  • 我不能,因为需要将我的 Task 类转换为 XML 文件。 XML 编码器不支持 LocalDate @James_D
  • 我对 XML 编码器的工作不多,但我很确定有办法做到这一点......
  • 您当然可以使用 JAXB 执行此操作:请参阅 stackoverflow.com/q/36156741
  • 看来你也可以使用XMLEncoderstackoverflow.com/q/41373566

标签: java javafx data-binding datepicker


【解决方案1】:

如果 Task.dateObjectProperty&lt;LocalDate&gt; 应该代表一个日期,它似乎更有意义。然后你可以像往常一样双向绑定它们:

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());

完全按照需要工作。

请注意,由于在 cmets 中您说您正在使用 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);

【讨论】:

    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多