Search code examples
cssjavafxstylesheet

JavaFX CSS Styling from Java


I want to assign a style class to an element.

I have a css:

.text-field{
    -fx-background-color: #333333;
    -fx-background-insets: 0 -1 -1 -1, 0 0 0 0, 0 -1 3 -1;
    -fx-text-fill: white; 
    -fx-prompt-text-fill: white;
    -fx-font-family: Trebuchet MS;
    -fx-font-size: 14px;
}

.text-field:focused{
    -fx-focus-color: white;
    -fx-prompt-text-fill: white;
    -fx-highlight-fill:  grey ;
}

And the java code I´m using:

JFXTextField textField = new JFXTextField();                    
textField.getStylesheets().add(this.getClass().getResource("/css/TextField_Style_Sheet.css").toExternalForm());
textField.getStyleClass().clear();
textField.getStyleClass().add("text-field");

The problem I´m having is that the ":focused" style is not being applied to this element. What am I doing wrong?

Already tested it using directly scenebuilder in the element and it seems that the setting in "Focus Color" and "UnFocus Color" options override the text-field:focused style. As the JFXTextField is created in runtime it seems the default Focus Color overrides the css text-field:focused style.

How can this be solved?


Solution

  • You replace all the style classes of the node with a single style class: text-field.

    Take a look at modena.css to see that the style of TextFields is defined in rules for style class text-input.

    These rules are also the only place where the CSS variable -fx-focus-color is used for TextFields. Since you make sure those rules are no longer applied you don't see any visible effect when modifying the -fx-focus-color variable.

    If you do want to keep the parts of the old style you should not remove the style classes that are added when creating the node and modify properties that don't suit your needs in your own style. If you clear the style classes you're responsible for rebuilding the look from scratch.