javaeventsjavafxeventfilter

Event filter on DatePicker fires twice for one action


I have this code to enable modifying date in datepicker using keyboard:

DatePicker startDatePicker = new DatePicker();
startDatePicker.addEventFilter(KeyEvent.KEY_PRESSED, (event) -> {

        if (event.getCode().equals(KeyCode.UP)){

                startDatePicker.setValue(startDatePicker.valueProperty().get().plusDays(1));
                event.consume();


        }else if (event.getCode().equals(KeyCode.DOWN)){

                startDatePicker.setValue(startDatePicker.valueProperty().get().minusDays(1));
                event.consume();


        }

    });

However no mater what I do the event fires twice for every keypress. I tried using KEY_PRESSED and KEY_RELEASED, consuming or not consuming the event but no matter what I do it always fires twice (tested using output to console, every keypress produced two lines). Right now I am working around it using boolean variable so the event only works every other time but there has to be a better solution than this.


Solution

  • I'm not completely sure why that is happening; it looks like the popup for the date picker receives the event, and redirects it to the date picker, and then the date picker itself receives the event independently. That's probably a bug. Is it enough of a work around to add the listener to the text field:

    startDatePicker.getEditor().addEventFilter(KeyEvent.KEY_PRESSED, ...);