Transparent background of a textarea in JavaFX 8

后端 未结 1 1763
攒了一身酷
攒了一身酷 2020-12-03 11:13

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,

相关标签:
1条回答
  • 2020-12-03 11:29

    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

    0 讨论(0)
提交回复
热议问题