Simsala
Simsala

Reputation: 67

Custom Datepicker Input Text with comma

I want to enter a custom format for a DatePicker in Javafx8. If I enter e.g. "21,2,15" by textinput i want the date picker to set the localdate to 21st February 2015. I could split the string in three parts and simply add the three INTs to a new localdate but how can i access my inputtext before/while hitting enter? 2nd possibilty: catch a comma(,) and instantly convert it into a dot (.) so while typing "21,2,15" it converts to "21.2.15" and with THIS format after hitting enter, the DatePicker adds 2015-02-21 as a localdate. So any chance to enter a date with "d,m,yy"?

Upvotes: 0

Views: 872

Answers (1)

James_D
James_D

Reputation: 209724

Specify a converter for the DatePicker and use an appropriate DateTimeFormatter to parse and format the date.

SSCEE:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class DatePickerWithCustomFormat extends Application {

    @Override
    public void start(Stage primaryStage) {
        DatePicker datePicker = new DatePicker();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d,M,y");
        datePicker.setConverter(new StringConverter<LocalDate>() {

            @Override
            public String toString(LocalDate date) {
                if (date == null) {
                    return "" ;
                }
                return formatter.format(date);
            }

            @Override
            public LocalDate fromString(String string) {
                if (string == null || string.isEmpty()) {
                    return null ;
                }
                return LocalDate.from(formatter.parse(string));
            }

        });

        datePicker.valueProperty().addListener((obs, oldDate, newDate) -> 
            System.out.println("Selected "+newDate));

        primaryStage.setScene(new Scene(new StackPane(datePicker), 375, 120));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Upvotes: 1

Related Questions