I have a simple Scene with this code:
scene.getStylesheets().add("packagename/testcss.css");
And my testcss.css is:
.button {
-fx-background-color: #DDFFA4;
}
.button:hover {
-fx-background-color: #9ACD32;
}
What i achieve is the nice effect that is aka hover when in web applications.
...
QUESTION
How can i achieve the same effect but without a separate css file, just via the setStyle method of my Button?
The problem is that setStyle accepts just the style definition and leave out the selector.
button.setStyle("-fx-background-color: #DDFFA4;");
The selector, in my hover case is the pseudo-class:
.button:hover
but where am I supposed to set it?
Moreover, the javadoc is explicit in excluding the selector from the setStyle method argument:
Note that, like the HTML style attribute, this variable contains style properties and values and not the selector portion of a style rule.
You can optionally set them css to be changed/updated programmatically when different events are triggered.. I added the following functions to the fxml files events against my checkin button.
As you note in your question, as of JavaFX 2.2, the css pseudoclasses aren't exposed as part of the public API you can use for style manipulation inside Java code.
If you want to change style attributes from Java code without using a stylesheet, you need to set the styles based on events or changelisteners. There are a couple of options in the sample below.
I'd only really do it in code rather than a stylesheet if colors needed to be really dynamic making use of stylesheets with predefined colors and styles problematic, or if there was some other aversion to using css stylesheets.
In JavaFX 8 there is be a public API which allows you (if you want to) to manipulate Region background colors without use of CSS.
Sample program output (with the Update button hovered):