I’m very happy with JavaFX 8 release that has DatePicker control, finally. Value of DatePicker Control is LocalDate data type, but you can convert it to Date Object if you want it. LocalDate class is a new class in Java 8. A LocalDate represents a year-month-day date without time. By default, LocalDate is using the system clock in the default time zone.
There is no convenience shortcut to manipulate value in DatePicker control. But, don’t worry we can create it. What I’m going to do is to ease user to manipulate value of DatePicker control using shortcuts. If the user would like to increase the day just press UP arrow on keyboard while DOWN arrow to decrease it.
We will take advantage of key-pressed-event to attach an eventFilter in the datepicker by calling addEventFilter method. It will filter UP and DOWN keyboard press and increase or decrease date accordingly. It also detect shift and control key combinations.
We use addEventFilter instead of addEventHandler because this method will be called before the event is consumed by any children controls. The filter is called when the node receives an Event of the specified type during the capturing phase of event delivery.
DatePicker datePicker = new DatePicker(); datePicker.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent event) -> { LocalDate value = datePicker.getValue(); if (value == null) { //give default value if there is no one value = LocalDate.now(); } if (event.getCode() == KeyCode.UP && event.isControlDown() && event.isShiftDown()) { //UP pressed, the control and shift are hold down, increase the year datePicker.setValue(value.plusYears(1)); } else if (event.getCode() == KeyCode.UP && event.isControlDown()) { //UP pressed, the control key is hold down, increase the month datePicker.setValue(value.plusMonths(1)); } else if (event.getCode() == KeyCode.UP) { //UP pressed, no modifier keys hold down, increase the day datePicker.setValue(value.plusDays(1)); } else if (event.getCode() == KeyCode.DOWN && event.isControlDown() && event.isShiftDown()) { //DOWN pressed, the control and shift are hold down, decrease the year datePicker.setValue(value.minusYears(1)); } else if (event.getCode() == KeyCode.DOWN && event.isControlDown()) { //DOWN pressed, the control key is hold down, decrease the month datePicker.setValue(value.minusMonths(1)); } else if (event.getCode() == KeyCode.DOWN) { // DOWN pressed, no modifier keys hold, decrease the day datePicker.setValue(value.minusDays(1)); } });
With his shortcut if you want to increase date just press UP arrow on your keyboard and DOWN arrow to decrease it. For increasing month press ctrl + UP arrow and ctrl + DOWN arrow to decrease it. For increasing year press ctrl + shift + UP arrow and + ctrl+ shift + DOWN arrow to decrease it.
For full source code, please get it here.