JavaFX Controls: DatePicker and ColorPicker Controls - dummies

JavaFX Controls: DatePicker and ColorPicker Controls

By Doug Lowe

In all, JavaFX has about 75 different controls you can choose from to build your user interfaces. Here are two more JavaFX controls to put in your toolbox.

ColorPicker

A color picker is a special type of combo box that lets the user choose a color. When the color picker is initially displayed, it looks like a button. When the user clicks it, a palette of colors appears from which the user may choose, as shown in this figure.

A color picker in JavaFX.
A color picker in JavaFX.

If the user doesn’t like the choices that are displayed in the color picker palette, the user can click the Custom Colors link at the bottom of the picker. This brings up a dialog box that lets the user craft a custom color, as shown in this figure.

Creating a custom color in JavaFX.
Creating a custom color in JavaFX.

To create a color picker, just use the default constructor:

ColorPicker cp = new ColorPicker();

You can read the color selected by the user via the getValue method:

Color c = cp.getValue();

The following example shows how you can add a listener for a color picker’s OnAction event to set the fill color of a rectangle named rect to the selected color:

cp.setOnAction(e ->
        r1.setFill(cp.getValue()) );

DatePicker

Like a color picker, a date picker is a special type of combo box that lets the user choose a date from a calendar-like display. Initially, the date picker looks like a text field. But when the user clicks it, a calendar display appears, as shown in this figure. The user can then choose a date, which the program can retrieve via the getValue method, which returns the date as a LocalDate.

A date picker in JavaFX.
A date picker in JavaFX.

The following example creates a date picker control and an OnAction event handler that sets the text value of a Label control named lbl to the date selected by the user:

DatePicker dp = new DatePicker();
dp.setOnAction(e ->
    {
        LocalDate date = dp.getValue();
        lbl.setText(date.toString());
    });