Search code examples
javacssjavafxdatepickerjavafx-8

JavaFX DatePicker set alignment of date value


When I use the Datepicker of JavaFX and use the full width of the node, the text of the date picker is not centered.

I tried with setStyle("-fx-alignment: center;") but this does not work.

enter image description here

I want something like this (made with paint):

enter image description here

How can I center the text? Here is the examplecode:

import java.time.LocalDate;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class JavaFxExample extends Application {

    private BorderPane borderPane;

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

    @Override
    public void start(Stage stage) {
        borderPane = new BorderPane();
        stage.setScene(new Scene(borderPane, 600, 400));
        stage.show();
        running();
    }

    private void running() {
        DatePicker datepicker = new DatePicker();
        datepicker.setValue(LocalDate.now());
        datepicker.setStyle("-fx-alignment: center;"); // this does not work :(
        datepicker.setPrefWidth(Double.MAX_VALUE);
        borderPane.setCenter(datepicker);
    }

}

Solution

  • Just add the following CSS (in a stylesheet file):

    .date-picker > .text-field  {
        -fx-alignment: center;
    }
    

    enter image description here