How to create a date picker using JavaFX?



Typically, a date picker displays a calendar, from which you can browse through different months and pick a date. The picked date is formatted and inputs into the system.

In JavaFX the javafx.scene.control.DatePicker class represents the date picker. This contains a text (date) filed and a date chooser. You can either enter the date manually or choose a date using the date chooser.

To create a date picker in your application, you need to instantiate this class. You can get the chosen date from the date picker by invoking the getValue() method.

Example

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class DatePickerExample extends Application {
   public void start(Stage stage) {
      //Creating label
      Text dobLabel = new Text("Date Of Birth:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      dobLabel.setFont(font);
      //Creating a date picker
      DatePicker datePicker = new DatePicker();
      //Creating HBox
      HBox box = new HBox(5);
      box.setPadding(new Insets(15, 50, 50, 50));
      box.getChildren().addAll(dobLabel, datePicker);
      //Setting the stage
      Scene scene = new Scene(box, 595, 260, Color.BEIGE);
      stage.setTitle("Date Picker Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output


Advertisements