FreeCode

Donate HTML/CSS JavaFX Java Home
JavaFX Starter Template JavaFX Labels JavaFX Buttons JavaFX Toggle Buttons JavaFX Radio Buttons and Toggle Groups JavaFX Checkboxes JavaFX Choice Boxes JavaFX Combo Boxes JavaFX Text Areas JavaFX Text Fields JavaFX List Views JavaFX Image Views JavaFX Color Pickers JavaFX Date Pickers JavaFX Resizable Split Pane Layouts JavaFX VBox (Vertical Box Layouts) JavaFX HBox (Horizontal Box Layouts) JavaFX Flow Pane Layouts JavaFX Tile Pane Layouts JavaFX Web Views

JavaFX Color Pickers

Code Description:

A single line of code can instantiate an amazing and useful Color Picker which allows for both custom colors and preset colors. The Color Picker gives you the ability to save custom colors and will allow you to pick colors using RGB (Red/Green/Blue), HSB (Hue/Saturation/Brightness), and Hexidecimal (Web) colors.

Color Picker Syntax:

ColorPicker colorPicker = new ColorPicker();

Full Runnable JavaFX Color Picker Code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Demo extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
		
        VBox root = new VBox();
		
	ColorPicker colorPicker = new ColorPicker();
		
	root.getChildren().add(colorPicker);
		
	primaryStage.setTitle("Color Picker Demo");
	primaryStage.setScene(new Scene(root, 200, 100));
	primaryStage.show();
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Note: You will NOT be able to copy and paste this code into your IDE unless you first set up JavaFX for your project. Check out this link if you need help setting up JavaFX:

JavaFX Comprehensive Setup Guide

Output:

Preset and Saved Colors Window

Preset and Saved Colors Window

Custom Color Window

Custom Color Window

Important Methods:

  • getValue() - Used to get the currently selected color.
  • setValue() - Used to set the current color in the color picker
  • getCustomColors() - Used to access your saved custom colors. You can get a specific color by specifying an index. EX: "colorPicker.getCustomColors().get(index)"
  • setDisable() - Used to make the color picker grayed out and unclickable. EX: "colorPicker.setDisable(true);"
  • setPrefSize() - Set the preferred width and height for the color picker.
  • setStyle() - Set an inline CSS-like style on the color picker. EX: "colorPicker.setStyle("-fx-background-color: green;");"
  • setVisible() - Show or hide the color picker from the scene. EX: "colorPicker.setVisible(false);"

Related Links:

JavaFX Date Pickers