Search code examples
cssjavafxoperator-precedence

how about css class prescedence in javafx


I want to add another css class for my component by example

.item{
-fx-background-color:blue;
-fx-border-radius:5;
}
.item-some{
-fx-background-color:red;
}

and in my code

control.getStyleClass().addAll("item","item-some");

but my control only get "item-some" style i want override only the color applying the second class as in css on web, can someone help me or give me a link to read about it? thanks.


Solution

  • This basically behaves as expected for me: the item with both style classes gets the properties defined for both selectors. If there are conflicts, such as fx-background-color in this example, the one defined later in the css file overrides the ones before it.

    Here's a complete test:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.Region;
    import javafx.stage.Stage;
    
    public class MultipleStyleClassTest extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            Region region1 = new Region();
            Region region2 = new Region();
            region1.getStyleClass().add("style-class-1");
            region2.getStyleClass().addAll("style-class-1", "style-class-2");
    
            HBox root = new HBox(region1, region2);
    
            Scene scene = new Scene(root);
            scene.getStylesheets().add("multiple-style-class-test.css");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    multiple-style-class-test.css is

    .style-class-1 {
        -fx-min-width: 300 ;
        -fx-min-height: 400 ;
        -fx-background-color: blue ;
        -fx-background-radius: 25 ;
    }
    
    .style-class-2 {
        -fx-background-color: red ;
    }
    

    and the result is

    enter image description here

    As can be seen, both region1 and region2 get the -fx-min-height, -fx-min-width, and -fx-background-radius properties defined for style-class-1. region1 gets the -fx-background-color defined for style-class-1; region2 displays the background color defined for style-class-2.