Search code examples
cssjavafxcolor-pickercolor-palette

JavaFX Color Picker without Color Chooser


I am displaying a lable for each series within a line chart instead of the chart legend symbol. When clicking on the lable a color picker is added to choose the series color. I am looking for a way to show only the palette and not the color choser (see here for definition)

enter image description here

Here is a code snippet extracting the clickable label part:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class LabelColorPicker extends Application {

@Override
public void start(Stage stage) throws Exception {

    Pane pane = new Pane();

    ColorPicker colorPicker = new ColorPicker() {
        @Override
        public void hide() {
            super.hide();
            pane.getChildren().remove(this);
        }
    };

    colorPicker.setValue(Color.BLUE);

    Label label = new Label("Series name");

    label.textFillProperty().bind(colorPicker.valueProperty());

    pane.getChildren().add(label);

    label.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> {

        pane.getChildren().add(colorPicker);
        colorPicker.show();
        colorPicker.layoutYProperty().bind(label.heightProperty());
    });


    Scene scene = new Scene(pane, 800, 600);
    stage.setScene(scene);
    stage.show();
}

}

Solution

  • Just call

    colorPicker.setVisible(false);
    

    If you want to avoid the space being occupied in the containing pane (I'm not sure why you are managing the layout yourself, instead of using e.g. a VBox), also call

    colorPicker.setManaged(false);