Select multiple dates with DatePicker

前端 未结 2 610
孤城傲影
孤城傲影 2021-01-14 02:39

I am trying to create a DatePicker that selects multiple dates. I am able to select multiple dates but I would like to keep the DatePicker open while I select them. Proble

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-14 02:51

    If you check DatePickerContent class, you can find that each time a new DateCell is created, an EventHandler of type MOUSE_CLICKED is added to it. This handler will call selectDayCell(DateCell) when the user clicks on a cell. selectDayCell(DateCell) sets the new date value and hides the DatePicker:

    protected void createDayCells() {
        final EventHandler dayCellActionHandler = ev -> {
            if (ev.getButton() != MouseButton.PRIMARY) {
                return;
            }
            DateCell dayCell = (DateCell)ev.getSource();
            selectDayCell(dayCell);
            lastFocusedDayCell = dayCell;
        };
        for (int row = 0; row < 6; row++) {
            for (int col = 0; col < daysPerWeek; col++) {
                DateCell dayCell = createDayCell();
                dayCell.addEventHandler(MouseEvent.MOUSE_CLICKED, dayCellActionHandler);
                dayCells.add(dayCell);
            }
        }
        dayCellDates = new LocalDate[6 * daysPerWeek];
    }
    
    public void selectDayCell(DateCell dateCell) {
        datePicker.setValue(dayCellDate(dateCell));
        datePicker.hide();
    }
    

    If you're using Java 9 or newer, you can extend DatePickerContent class and override the selectDayCell(DateCell) method to not hide the DatePicker after a cell is selected:

    public void selectDayCell(DateCell dateCell) {
        datePicker.setValue(dayCellDate(dateCell));
    }
    

    Unfortunately, in Java 8, DatePickerContent has a package-private constructor so you can't extend from it. As a workaround, you can add another EventHandler on mouse click that will show the DatePicker again after a cell is clicked:

    EventHandler mouseClickedEventHandler = clickEvent -> {
        if (clickEvent.getButton() == MouseButton.PRIMARY) {
            datePicker.show();
        }
        clickEvent.consume();
    };
    

    In your cell factory:

    @Override
    public void updateItem(LocalDate item, boolean empty) {
        super.updateItem(item, empty);
        //...
        if (item != null && !empty) {
            //...
            addEventHandler(MouseEvent.MOUSE_CLICKED, mouseClickedEventHandler);
        } else {
            //...
            removeEventHandler(MouseEvent.MOUSE_CLICKED, mouseClickedEventHandler);
        }
    }
    

提交回复
热议问题