Eerik Muuli Eerik Muuli - 5 months ago 46
CSS Question

JavaFX setStyle with -fx-background-color paints only the edges of a TextArea

So, I have a dynamically created list of

TextArea
's and I want to paint them depending on which
CheckBox
I select. Currently, it only colors the borders, but not the inside of the
TextArea
.

Here is my code:

if (cb.isSelected()) {
ta.setStyle("-fx-background-color:#38ee00;");
}
if (cb2.isSelected()) {
ta.setStyle("-fx-background-color:orangered;");
}
if (!cb2.isSelected() && !cb.isSelected()) {
ta.setStyle("-fx-background-color:white;");
}


And here is the result that it brings:

enter image description here

If you need any other information, please feel free to let me know.

Answer

You actually need to style the .content region that is a child of the TextArea (see CSS Reference: TextArea - Substructure).

You can get that node using lookup, but only after the skin is applied, which does not happen until layout. Then however you can do something like this:

Region content = (Region) ta.lookup(".content");
content.setStyle("-fx-background-color:orangered;");

An alternative would be using a CSS stylesheet and changing the class of the TextArea (provided only a limited number of colors is used):

.text-area.color-orangered .content {
     -fx-background-color: orangered;
}

.text-area.color-white .content {
     -fx-background-color: white;
}

.text-area.color-green .content {
    ...
// remove old class for coloring
ta.getStyleClass().removeIf(s -> s.startsWith("color-"));

// add new class
ta.getStyleClass().add("color-orangered");