Changing language in JavaFX 8 DatePicker

When adding a DatePicker to my application, I get this:

DatePicker

I am assuming this is because I am using Hebrew on my computer. How do I change the language of the DatePicker to English?

+3


source to share


1 answer


You can define the default locale for your Java Virtual Machine invocation instance:

Locale.setDefault(Locale.ENGLISH);

      

by the method start

. If you also want to implement a custom formatter for your text editor, you must add a locale to the formatter as well.

This is just an example:

private final DateTimeFormatter formatter = 
        DateTimeFormatter.ofPattern("EEEE, d.MM.uuuu", Locale.ENGLISH);

@Override
public void start(Stage primaryStage) {
    Locale.setDefault(Locale.ENGLISH);

    DatePicker datePicker=new DatePicker();
    datePicker.setValue(LocalDate.now());
    datePicker.setConverter(new StringConverter<LocalDate>() {

        @Override
        public String toString(LocalDate object) {
            return object.format(formatter);
        }

        @Override
        public LocalDate fromString(String string) {
            return LocalDate.parse(string, formatter);
        }
    });
    StackPane root = new StackPane(datePicker);
    Scene scene = new Scene(root, 400, 400);

    primaryStage.setScene(scene);
    primaryStage.show();
}

      

EDIT



DatePicker

Uses by design Locale.getDefault()

in all formats applied to controls displayed in a popup. This can be verified in class com.sun.javafx.scene.control.skin.DatePickerContent

.

If you have not provided a custom skin for the control changing these formats to change the content DatePicker

to English while avoiding further changes to other localized controls, this might be a workaround:

private final Locale myLocale = Locale.getDefault(Locale.Category.FORMAT);

@Override
public void start(Stage primaryStage) {
    DatePicker datePicker=new DatePicker();
    datePicker.setValue(LocalDate.now());
    datePicker.setOnShowing(e-> Locale.setDefault(Locale.Category.FORMAT,Locale.ENGLISH));
    datePicker.setOnShown(e-> Locale.setDefault(Locale.Category.FORMAT,myLocale));
    ...
}

      

EDIT 2

Reverting to the setOnShown

original locale too soon because if the user changes the month, the original locale is used and will not display correctly. It must be disabled on both on setOnHiding

and off to work setOnAction

.

private final Locale myLocale = Locale.getDefault(Locale.Category.FORMAT);

@Override
public void start(Stage primaryStage) {
    DatePicker datePicker=new DatePicker();
    datePicker.setValue(LocalDate.now());
    datePicker.setOnShowing(e-> Locale.setDefault(Locale.Category.FORMAT,Locale.ENGLISH));
    datePicker.setOnHiding(e-> Locale.setDefault(Locale.Category.FORMAT,myLocale));
    datePicker.setOnAction(e-> Locale.setDefault(Locale.Category.FORMAT,myLocale));
    ...
}

      

+6


source







All Articles