Search code examples
javaeventsjavafxcolorscolor-picker

Is it possible to get the 'new color' in JavaFx ColorPicker?


I'm trying to get the 'new color' value from a ColorPicker ('nouvelle couleur' in my image because it's french).

This is what I'm talking about

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

When you set up a EventHandler for a ColorPicker, it only returns the value of the ColorPicker when you close it.

So I was wondering, is it possible to get this value ?

Sorry if there are any mistake, English is not my native language.


Solution

  • Yes, the valueProperty() from the ColorPicker control is updated every time you modify the selection in the dialog. Only if you cancel the change, it is backed out.

    So you just need to add a listener to that property or bind it as required.

    @Override
    public void start(Stage primaryStage) {
        ColorPicker picker = new ColorPicker(Color.ALICEBLUE);
        Text text = new Text("Color Picker");
        VBox root = new VBox(10, text, picker);
        root.setAlignment(Pos.CENTER);
    
        text.fillProperty().bind(picker.valueProperty());
    
        Scene scene = new Scene(root, 300, 250);
    
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    color picker