Search code examples
javacssjavafxcolor-picker

How to set pane colour from colour picker


I have some code, in javafx, that has a pane that works like a paint canvas. I need to be able to fill the background color of the pane from a color picker.

Currently I have a Color variable that gets the color chosen from the color picker and I try to set it to my Pane (named canvas) as below:

Color newColour = backgroundColourPicker.getValue();
canvas.setStyle("-fx-background-color: " + newColour + ";");

However I get this output:

June 11, 2022 7:47:57 PM javafx.css.CssParser term
WARNING: CSS Error parsing '*{-fx-background-color: 0x00ffffff;}: Unexpected token '0x' at [1,24]

How do I either swap my Color value to a String to be able to remove the leading 0x and make it work or how do I get my Pane to accept the color value as a Color?


Solution

  • I have found this code worked for me if anyone needs it in the future:

    Color newColour = backgroundColourPicker.getValue();
    Double red = newColour.getRed()*100;
    int rInt = red.intValue();
    Double green = newColour.getGreen()*100;
    int gInt = green.intValue();
    Double blue = newColour.getBlue()*100;
    int bInt = blue.intValue();
    String hex = String.format("#%02X%02X%02X", rInt, gInt, bInt);
    canvas.setStyle("-fx-background-color: " + hex + ";");