Search code examples
javajavafxjavafx-css

How to style checkbox's css in-line using setStyle()


Let me keep it short.

So. I know you can style the CheckBox's .box in css like:

.check-box > .box {
    -fx-background-color: white;
}

but I'm not sure how to in-line. Please just provide an example code. Thanks.


Solution

  • Inline styles only apply to the node itself, not to children. You won't be able to style children using inline styles directly, unless you're willing to use lookup to access the child node. This only works after the skin is created though which usually happens just before the first layout pass which can make this problematic, if you want to do it from fxml/controller initialize.

    modena.css contains the following declarations for the .box child of (un)focused CheckBoxes though:

    -fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
    
    -fx-background-color: -fx-focus-color, -fx-inner-border, -fx-body-color, -fx-faint-focus-color, -fx-body-color;
    

    i.e. it contains lookedup colors which are inherited from the parent and thus can be assigned using inline css on the CheckBox:

    checkBox.setStyle("-fx-body-color: red;");