JavaFX datepicker not updating value

The bug log that I added above had the answer. You can access the string value of the textbox via this code:

datePicker.getEditor().getText();

So setting the textbox value can be done via:

datePicker.setValue(datePicker.getConverter()
    .fromString(datePicker.getEditor().getText()));

I'm adding an event to the lost focus event, that will force the datepicker value to be updated


And the working code:

public DatePicker getDatePicker(DtDate defaultDate, int width){
    DatePicker dtpckr = new DatePicker();
    dtpckr.setMaxWidth(width);
    dtpckr.setMinWidth(width);
    dtpckr.setConverter(new StringConverter<LocalDate>() {
        private DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy/MM/dd");
        @Override
        public String toString(LocalDate localDate) {
            if(localDate==null)
                return "";
            return dateTimeFormatter.format(localDate);
        }
        @Override
        public LocalDate fromString(String dateString) {
            if(dateString==null || dateString.trim().isEmpty())
                return null;
            try{
                return LocalDate.parse(dateString,dateTimeFormatter);
            }
            catch(Exception e){
                //Bad date value entered
                return null;
            }
        }
    });
    dtpckr.setPromptText("yyyy/MM/dd");
    dtpckr.setValue(LocalDate.parse(defaultDate.toString(), DateTimeFormatter.ofPattern("yyyy/MM/dd")));
    //This deals with the bug located here where the datepicker value is not updated on focus lost
    //https://bugs.openjdk.java.net/browse/JDK-8092295?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
    dtpckr.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (!newValue){
                dtpckr.setValue(dtpckr.getConverter().fromString(dtpckr.getEditor().getText()));
            }
        }
    });
    return dtpckr;
}

I recently fixed this issue in the newest JavaFX version: https://github.com/openjdk/jfx/pull/679

So when JavaFX 18-ea+9 will be released you can use it and remove the workaround. :-)


@Draken's answer needs a little extra. If the user types an invalid date the code will throw a DateTimeParseException. You can emulate the DatePicker's own behaviour thus:

dtpckr.getEditor().focusedProperty().addListener((obj, wasFocused, isFocused)->{
      if (!isFocused) {
         try {
             dtpckr.setValue(dtpckr.getConverter().fromString(dtpckr.getEditor().getText()));
         } catch (DateTimeParseException e) {
                dtpckr.getEditor().setText(dtpckr.getConverter().toString(dtpckr.getValue()));
         }
      }
});