How to set Minimum and maximum date in Datepicker Calander in JavaFx8?

雨燕双飞 提交于 2019-12-08 16:47:48
Johan Kaewberg

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!