JavaFX Tutorial - JavaFX ColorPicker








The color picker control enables users to select a color from the available range, or set an additional color by specifying an RGB or HSB combination.

JavaFX ColorPicker control has the color chooser, color palette, and custom color dialog window.

ColorPicker Creation

The following code creates a Color Picker Control with empty constructor and the color picker control uses the default color, which is WHITE.

ColorPicker colorPicker1 = new ColorPicker();

We can also provide color constant as the currently selected color.

ColorPicker colorPicker2 = new ColorPicker(Color.BLUE);

We can also provide web color value as the currently selected color

ColorPicker colorPicker3 = new ColorPicker(Color.web("#EEEEEE"));




Example

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Main extends Application {
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new HBox(20), 400, 100);
    HBox box = (HBox) scene.getRoot();
    final ColorPicker colorPicker = new ColorPicker();
    colorPicker.setValue(Color.RED);

    final Text text = new Text("Color picker:");
    text.setFill(colorPicker.getValue());

    colorPicker.setOnAction((ActionEvent t) -> {
      text.setFill(colorPicker.getValue());
    });

    box.getChildren().addAll(colorPicker, text);

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




Custom Colors

getCustomColors() method returns the created custom colors as an ObservableList of the Color objects.

ObservableList<Color> customColors = colorPicker.getCustomColors();
colorPicker.setValue(customColors.get(index));