Search code examples
javafxdatepicker

Greying out dates in DatePicker with javafx doesn't work as intended


I only want the user to select dates from today + 10 days in the future. But as you can see it works perfectly for the current month. But in February you can again select the dates although they are after the 10 days I want to be selectable. I only want to make 17.1. - 27.1. Selectable.

enter image description here

This is what i tried: (This doesn't look good but it's enough to show the issue and to you guys to help me.)

 @Override
    public void start(Stage stage) throws IOException {
        DatePicker dpDate = new DatePicker();
        dpDate.setDayCellFactory(param -> new DateCell() {
            @Override
            public void updateItem(LocalDate date, boolean empty) {
                super.updateItem(date, empty);
                setDisable(empty || date.compareTo(LocalDate.now()) > 10 || date.compareTo(LocalDate.now()) < 0);
            }
        });
        Scene scene = new Scene(dpDate, 320, 240);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();
    }

Solution

  • LocalDate.compareTo() just guarantees to return a negative, zero, or a positive, depending on whether or not the date is before, equal to, or after the supplied date. There's no guarantee (or expectation) it returns the number of days between the two dates.

    Use

        dpDate.setDayCellFactory(param -> new DateCell() {
            @Override
            public void updateItem(LocalDate date, boolean empty) {
                super.updateItem(date, empty);
                setDisable(empty || 
                           date.isBefore(LocalDate.now()) ||
                           date.isAfter(LocalDate.now().plusDays(10))
                );
            }
        });