JavaFX inline CSS hover effect

I am building a costume button by extending from a Label. I know that you can use CSS within .java files with:

setStyle("-fx-background-color: #101010");

which is pretty cool and I am using this quite often.

But there is my problem: It seems like this doesn't work for hover effects. In an external CSS file you can have:

#LabelButton:hover {
  -fx-background-color: #aaaaaa;
}

I would like to have this feature with "XXX:hover" inside my Java File because the hex color code must be variable and this isn't possible when using external CSS files. So what I kinda want to have it this:

setStyle("hover:-fx-background-color: #101010");

But I can't find the right syntax for it let alone there is a syntax. If there is no such feature, how should I do it then? Thanks!

Upvotes: 2

Views: 4930

Answers (1)

fabian
fabian

Reputation: 82451

There is no way to use selectors of any kind in inline CSS. The inline style is always applied to the node regardless of it's state (with the exception of you assigning the corresponding node property).

You could bind the style property to the hover property of the node.

myButton.styleProperty().bind(Bindings.when(myButton.hoverProperty())
                                      .then("-fx-background-color: #101010")
                                      .otherwise("-fx-background-color: #aaaaaa"));

This could become very ugly if you e.g. want to style focused buttons and pressed buttons differently. For this reason I recommend combining CSS and inline CSS to achieve the desired style:

You can define your own variables color variables in CSS:

stylesheet

.label-button { /* using style class for selector (ids are for single nodes) */
    /* assign default values */
    -fx-normal-background: yellow;
    -fx-hovered-background: red;

    -fx-background-color: -fx-normal-background;
}

.label-button:hover {
    -fx-background-color: -fx-hovered-background;
}

java code

myButton.setStyle("-fx-normal-background: #101010; -fx-hovered-background: #aaaaaa;");

Upvotes: 5

Related Questions