Transparent background of a textarea in JavaFX 8
Asked Answered
F

1

16

Since I am using JavaFX 8, all my textareas do not apply the transparency that has been defined in the corresponding css. It works fine in Java 7, but for the release candidate of JavaFX 8, I can't get it to behave like before.

EDIT: This question is about JavaFX TextArea, not a JTextArea.
-fx-background-color: rgba(53,89,119,0.2); does not have any effect on the textarea anymore, although it should have an alpha value of 0.2, but it is opague...

Is that a known issue?

Feel answered 21/2, 2014 at 14:2 Comment(1)
Does anyone has a hint for me?Feel
M
27

The TextArea consists of several nodes. To make the background transparent it is necessary to change the background of the child panes as well (TextArea,ScrollPane,ViewPort,Content). This can be accomplished via CSS.

CSS Example:

.text-area {
    -fx-background-color: rgba(53,89,119,0.4);
}

.text-area .scroll-pane {
    -fx-background-color: transparent;
}

.text-area .scroll-pane .viewport{
    -fx-background-color: transparent;
}


.text-area .scroll-pane .content{
    -fx-background-color: transparent;
}

The same can be accomplished via code. The code shouldn't be used for production. It's just for demonstrating the node structure.

Code Example (makes all backgrounds fully transparent):

    TextArea textArea = new TextArea("I have an ugly white background :-(");
    // we don't use lambdas to create the change listener since we use
    // the instance twice via 'this' (see *)
    textArea.skinProperty().addListener(new ChangeListener<Skin<?>>() {

        @Override
        public void changed(
          ObservableValue<? extends Skin<?>> ov, Skin<?> t, Skin<?> t1) {
            if (t1 != null && t1.getNode() instanceof Region) {
                Region r = (Region) t1.getNode();
                r.setBackground(Background.EMPTY);

                r.getChildrenUnmodifiable().stream().
                        filter(n -> n instanceof Region).
                        map(n -> (Region) n).
                        forEach(n -> n.setBackground(Background.EMPTY));

                r.getChildrenUnmodifiable().stream().
                        filter(n -> n instanceof Control).
                        map(n -> (Control) n).
                        forEach(c -> c.skinProperty().addListener(this)); // *
            }
        }
    });

Further reference: JavaFX CSS Documentation

Message answered 28/2, 2014 at 23:57 Comment(3)
This is a really clever example.Posen
Thanks, that did it. Although I can confirm that it worked without this in JDK 1.7!Feel
How to do the same for TextArea only if it is not selected?Logjam

© 2022 - 2024 — McMap. All rights reserved.