javauser-interfacejavafxcolor-picker

JavaFX open Color Picker's Dialog on Custom Action Event


I want to launch the Color Picker's Dialog window and get the selected color as output. In my case I want this window to launch from clicking on a Rectangle object instead of the ColorPicker component.

I'm having trouble finding out what the class/method is for launching this window since all online resources just point me to ColorPicker examples which I want to avoid. I tried checking the documentation without any luck so if you guys know how to help me I would be very grateful to you.


Solution

  • I think you are asking how to make the color picker's popup appear without actually showing the color picker control. You need to have the color picker in the scene graph for it to work; however you can just make it invisible. Note that it will still be placed in the scene graph and its location will determine the location of the popup.

    Here's a minimal example:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.ColorPicker;
    import javafx.scene.layout.Pane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;
    
    public class HelloApplication extends Application {
        @Override
        public void start(Stage stage) {
            Rectangle rect = new Rectangle(100, 20, 200, 40);
            ColorPicker picker = new ColorPicker();
            picker.setVisible(false);
            Pane root = new Pane(rect, picker);
            rect.setStroke(Color.BLACK);
            rect.fillProperty().bind(picker.valueProperty());
            rect.setOnMouseClicked(e -> {
                // move the (invisible) color picker so the popup appears at the mouse:
                picker.relocate(e.getX(), e.getY() - picker.getHeight());
                picker.show();
            });
            Scene scene = new Scene(root, 400, 80);
            stage.setScene(scene);
            stage.show();
        }
    
        public static void main(String[] args) {
            launch();
        }
    }
    

    Here is how this looks at startup:

    enter image description here

    and here is the result of clicking on the rectangle:

    enter image description here