Search code examples
javafxjavafx-datepicker

How to show/open JavaFX DatePicker editor to a specific calendar date without setting any value in its textbox?


I wish to enable date picking for a time range Jan 2000 - Dec 2014 and have disabled dates outside this range and want to open the DatePicker editor to a date within this range without setting value(setValue() or Constructor) to it, since I want the text box empty. Can this be done?


Solution

  • You can set date you need by constructor or setValue and clear textbox with picker.getEditor().clear(). To disable dates from outside you can set custom DateCellFactory:

        LocalDate minDate = LocalDate.of(2000, Month.JANUARY, 1);
        LocalDate maxDate = LocalDate.of(2014, Month.DECEMBER, 31);
        DatePicker picker = new DatePicker(minDate.plusYears(2));
        picker.setDayCellFactory((p) -> new DateCell() {
            @Override
            public void updateItem(LocalDate ld, boolean bln) {
                super.updateItem(ld, bln);
                setDisable(ld.isBefore(minDate) || ld.isAfter(maxDate));
            }
        });
        Platform.runLater(() -> {
            picker.getEditor().clear();
        });