ddacrs
ddacrs

Reputation: 153

JavaFX - Change CSS specific values in runtime

I am doing a JavaFX application using a base css file.

I would like to have a feature where the user can select a base color, maybe using a Color Picker or something like that and I will change the css file to calculate the colors using this as base.

Or maybe a custom way to use derive method inside the CSS file using variables instead of static colors?

Thanks for any help!

Upvotes: 0

Views: 521

Answers (1)

Uluk Biy
Uluk Biy

Reputation: 49195

See the predefined colors of JavaFX from modena.css (or caspian.css for older JavaFX-2). For example. These colors are base for the most controls of JavaFX, but there are of course more specific colors defined for some controls only.

You can change them on runtime, and apply to top level (or any) pane, i.e. parent root of scene:

Color selectedColor = colorPicker.getValue();

String rgb = getRgbString( selectedColor );
myScene.getRoot().setStyle( "-fx-accent: " + rgb + "; -fx-focus-color:" + rgb );

where

private String getRgbString( Color color )
{
    int r = ( int ) Math.round( color.getRed() * 255.0 );
    int g = ( int ) Math.round( color.getGreen() * 255.0 );
    int b = ( int ) Math.round( color.getBlue() * 255.0 );

    return "rgb(" + r + "," + g + "," + b + ")";
}

You may also make the Color more brighter, darker and/or derive new color from it. Refer to api.

Upvotes: 1

Related Questions