Search code examples
javajavafxdatepickerjavafx-8javafx-bindings

How to get BooleanBinding from comparing 2 DatePickers?


I have two DatePickers and one Button on the GUI. I need to disable the button whenever the first datePicker has a date that is NOT before the second datePicker's date. i.e. before is false in the following snippet:

LocalDate date1 = dpFromDate.getValue();
LocalDate date2 = dpToDate.getValue();
boolean before = date1.isBefore(date2);
button.setDisable(!before);

using Bindings APIs.

BooleanBinding bb = ???;
button.disableProperty().bind(bb);

Here is my working solution, but I believe there is a better API to handle such situation:

BooleanBinding bb = Bindings.selectInteger(dpFromDate.valueProperty(), "year")
         .greaterThanOrEqualTo(Bindings.selectInteger(dpToDate.valueProperty(), "year"));

bb = bb.or(
       Bindings.selectInteger(dpFromDate.valueProperty(), "year")
       .isEqualTo(Bindings.selectInteger(dpToDate.valueProperty(), "year"))
  .and(Bindings.selectInteger(dpFromDate.valueProperty(), "monthValue")
       .greaterThanOrEqualTo(Bindings.selectInteger(dpToDate.valueProperty(), "monthValue")))
   );

bb = bb.or(
       Bindings.selectInteger(dpFromDate.valueProperty(), "year")
       .isEqualTo(Bindings.selectInteger(dpToDate.valueProperty(), "year"))
  .and(Bindings.selectInteger(dpFromDate.valueProperty(), "monthValue")
      .isEqualTo(Bindings.selectInteger(dpToDate.valueProperty(), "monthValue")))
  .and(Bindings.selectInteger(dpFromDate.valueProperty(), "dayOfMonth")
      .greaterThanOrEqualTo(Bindings.selectInteger(dpToDate.valueProperty(), "dayOfMonth")))
   );

Solution

  • Just create a BooleanBinding depending on the DatePicker values that compares both dates. This way you don't have to write the functionality yourself and even more important - you don't need to create such a complicated binding:

    BooleanBinding bb = Bindings.createBooleanBinding(() -> {
        LocalDate from = dpFromDate.getValue();
        LocalDate to = dpToDate.getValue();
    
        // disable, if one selection is missing or from is not smaller than to
        return (from == null || to == null || (from.compareTo(to) >= 0));
    }, dpFromDate.valueProperty(), dpToDate.valueProperty());
    
    button.disableProperty().bind(bb);