5 Replies Latest reply on Nov 16, 2011 9:59 PM by zonski

    Removing CSS style classes?

    zonski
      This is partly a question on whether this is expected behaviour or an unfortunate side effect, and partly a heads-up to anyone doing anything similar.

      The summary: removing a 'styleclass' from a Node does not remove the styling from the node

      If, for example, I have a Label and I add a styleclass to it that makes the border red, when the label is rendered the red border is applied to the Label. If I then remove that styleclass, there is now nothing on that Label telling the CSS engine to update the border so the engine now leaves the border untouched - i.e. it stays red. The only way it would get set back, is if the original style of the Label had a border setting that the CSS engine could then apply.

      For me, this is not what I was expecting and I spent a fair bit of time chasing my tail on this. My way of thinking was that when I remove the style class it would revert the label back to exactly how it was before I added the style. Was my way of thinking wrong or is this a flaw in the CSS approach that should be logged in JIRA?

      Below is some sample code that demonstrates the problem. I've used a default style that clears the background but does not clear the border - when you click on the button the background changes colour, but once the border is set, it is set for life.

      TestApp.java
      public void start(Stage stage) throws Exception
      {
          FlowPane root = new FlowPane(10, 10);
      
          final Label styledLabel = new Label("Use the toggle button to turn on and off highlight for this label");
          styledLabel.getStyleClass().add("normal");
          root.getChildren().add(styledLabel);
      
          ToggleButton button = new ToggleButton("Show Highlight");
          button.selectedProperty().addListener(new ChangeListener<Boolean>()
          {
              public void changed(ObservableValue<? extends Boolean> source, Boolean wasSelected, Boolean isSelected)
              {
                  if (isSelected)
                  {
                      styledLabel.getStyleClass().add("highlighted");
                  }
                  else
                  {
                      styledLabel.getStyleClass().remove("highlighted");
                  }
              }
          });
          root.getChildren().add(button);
      
          Scene scene = new Scene(root, 800, 600);
          scene.getStylesheets().add("styles.css");
          stage.setScene(scene);
          stage.show();
      }
      styles.css
      .normal {
          -fx-padding: 10;
          -fx-background-color: null;
      }
      
      .highlighted {
          -fx-border-radius: 6;
          -fx-border-color: red;
          -fx-border-width: 1;
          -fx-background-color: #ff9999;
          -fx-background-radius: 6;
      }