javafx datepicker how to customize

前端 未结 1 1920
生来不讨喜
生来不讨喜 2020-12-11 06:00

I have the simple code for date picker which disables all the dates which are before the chosen one, but I need to be able to disable other dates as well (like for example:1

相关标签:
1条回答
  • 2020-12-11 06:46

    If you want to have several ranges of dates to disable, you can create this POJO:

    class DisabledRange {
    
        private final LocalDate initialDate;
        private final LocalDate endDate;
    
        public DisabledRange(LocalDate initialDate, LocalDate endDate){
            this.initialDate=initialDate;
            this.endDate = endDate;
        }
    
        public LocalDate getInitialDate() { return initialDate; }
        public LocalDate getEndDate() { return endDate; }
    
    }
    

    And now in you can define a collection of ranges to disable in your calendar. For instance:

    private final ObservableList<DisabledRange> rangesToDisable = 
        FXCollections.observableArrayList(
            new DisabledRange(LocalDate.of(2014,10,17), LocalDate.of(2014,10,19)),
            new DisabledRange(LocalDate.of(2014,10,27), LocalDate.of(2014,10,29)));
    

    Finally, you just need to check in the Callback if the item is within any of these ranges:

    @Override
    public void updateItem(LocalDate item, boolean empty) {
        super.updateItem(item, empty);
    
        boolean disable = rangesToDisable.stream()
                .filter(r->r.initialDate.minusDays(1).isBefore(item))
                .filter(r->r.endDate.plusDays(1).isAfter(item))
                .findAny()
                .isPresent();
    
        if (item.isBefore(checkInDatePicker.getValue().plusDays(1)) || 
                disable) {
                setDisable(true);
                setStyle("-fx-background-color: #ffc0cb;");
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题