Peter Penzov
Peter Penzov

Reputation: 1658

Set css file for default skin

I created css style sheet based on caspian.css. My question is how I can load the new css skin as default skin?

And also how I can change the skins during runtime?

Upvotes: 0

Views: 503

Answers (1)

fabian
fabian

Reputation: 82461

You can either add the stylesheet directly to the Scene or to any Parent to apply it to the node and all decendants. Both classes have a method getStylesheets() that returns a ObservableList<java.lang.String>, that contains the URLs of the stylesheets applied to the object. Modify this list!

If you use fxml, you can specify the stylesheet there too (Of course this will only set the a initial stylesheet).

This is an example how to add the stylesheet at the creation of the scene. Of course you can remove the stylesheet from the list at any time and add another. Style.css is the stylesheet I want to add here and to a.b the package that contains the stylesheet.

// Load some content from some fxml file; Style.css not added there
Parent parent = (Parent) fxmlLoader.load(
       getClass().getResourceAsStream("MainFrame.fxml"));

// create scene with content
Scene scene = new Scene(parent);
// alternatively use Node.getScene() for any node to get the scene    

// add the stylesheet
scene.getStylesheets().add(
           getClass().getClassLoader().getResource("a/b/Style.css").toString());
// ...

ObservableList<T> extends java.util.List<T> and should be easy to use.




Note that the behaviour sometimes may not be quite as expected. e.g. the popup that shows, if you click on a combobox is no decendant of the combobox and the paths from these nodes to from the root node of the scene should have only the root node in common. Therefore the popup will not be styled, if you add the stylesheet to the Pane that contains the combobox (if this is not the root node of the scene).

The following picture contains a screenshot of a combobox with a styled popup. This only works, since the css-file was added to the scene instead of the AnchorPane, that contains the ComboBox. I used different css-classes for the items to color them. (The red rect and text is not part of my application of course)

Combobox Popup

These are the style classes i used

.indexed-cell.class-value-bad-1 {
    -fx-background-color: orange;
}

.indexed-cell.class-value-good-1 {
    -fx-background-color: forestgreen;
}

.indexed-cell.class-value-normal {
    -fx-background-color: white;
}

Upvotes: 1

Related Questions