How to set Minimum and maximum date in Datepicker

2019-08-15 12:03发布

问题:

Please help.

How Can we set min and max date in date picker calendar in javafx8?

回答1:

Or why not

minDate = LocalDate.of(1989, 4, 16);
maxDate = LocalDate.now();
datePicker.setDayCellFactory(d ->
           new DateCell() {
               @Override public void updateItem(LocalDate item, boolean empty) {
                   super.updateItem(item, empty);
                   setDisable(item.isAfter(maxDate) || item.isBefore(minDate));
               }});

No need to create an extra datepicker just to store the max date.



回答2:

It is possible to limit the dates available for being selected by user by disabling those days on a dayCellFactory and setting those dates range to you DatePicker, official docs can be found here, here is an example:

DatePicker myDatePicker = new DatePicker(); // This DatePicker is shown to user
DatePicker maxDate = new DatePicker(); // DatePicker, used to define max date available, you can also create another for minimum date
maxDate.setValue(LocalDate.of(2015, Month.JANUARY, 1)); // Max date available will be 2015-01-01
final Callback<DatePicker, DateCell> dayCellFactory;

dayCellFactory = (final DatePicker datePicker) -> new DateCell() {
    @Override
    public void updateItem(LocalDate item, boolean empty) {
        super.updateItem(item, empty);
        if (item.isAfter(maxDate.getValue())) { //Disable all dates after required date
            setDisable(true);
            setStyle("-fx-background-color: #ffc0cb;"); //To set background on different color
        }
    }
};
//Finally, we just need to update our DatePicker cell factory as follow:
myDatePicker.setDayCellFactory(dayCellFactory);

Now myDatePicker will not allow user to select dates after 2015-01-01 (Remeber, dates will be shown but no availble to be selected), here you can also create another temporary datePicker for Min date for setting available dates ranges, by the way these code have to be placed on initialize method of java controller



标签: javafx-8