Samstag, 21. Januar 2012

JavaFX Calendar Control

I've had much fun with JavaFX 2.0 recently and decided to develop a DatePicker / Calendar control, because it doesn't exist yet, and it would be a funny little project which would made me learn a lot about JavaFX.

So here it is (here are the sources):

The control consists of three views: A month view (which shows the current month), a year view (which shows the current year with its months) and a decades view (which shows two decades):

The behavior and navigation is similar to the JavaScript MooTools Calendar.

  • Localization
  • Easy navigation through months, years and decades.
  • CSS Styling
  • Disable certain week days or dates
  • Show/hide the "Today" Button
  • Show/hide the week numbers
  • Set custom date format (by default it is taken from the locale)
  • Set custom prompt text (by default it is taken from the date format pattern)
  • Auto-parsing the text field, when focus is lost and while typing (invalid input results in a red-bordered text field)
  • Cool animations :)

You can just instantiate the Date Picker in a usual way and treat it as a normal control.

DatePicker datePicker = new DatePicker();

There are some properties directly on the date picker control, and some more on the calendar view. E.g. if you want to enable the today button, you have to do it on the calendar view:


Setting the locale:

You can either pass a locale in the constructor or you can use the locale property to change the locale later.

The locale is directly used to determine the calendar, e.g. whether the first day of the week is Sunday or Monday, or if the Gregorian calendar or the Buddhist calendar should be used. (Java only knows these two).

Setting the calendar:

If you want to use your custom calendar (must be derived from java.util.Calendar or treat language and calendar independently, you can do it by setting the calendar explicitly like:

datePicker.getCalendarView().setCalendar(new BuddhistCalendar());

Which would look like:

How do I get the selected date?

Probably the most important part. There's are property selectedDate, which you can use. If the field is left without a valid date it becomes null otherwise it gives you the date.


The control uses only JavaFX css properties for styles. That means you can easily change the -fx-base to some other color and you get the following result: