简体   繁体   中英

Transparent Stage with transparent ScrollPane is not transparent

Here I have a method which generates a Stage that should be transparent with a ScrollPane of a bunch of rectangles.

private Stage createStage()
    {
        Stage stage = new Stage(StageStyle.TRANSPARENT);

        FlowPane flw = new FlowPane();
        flw.setBackground(Background.EMPTY);

        Random gen = new Random(5);
        for (int i = 0; i < 50; i++)
        {
            int size = 50 + gen.nextInt(50);
            flw.getChildren().add(new Rectangle(size, size, Color.web("rgb(" + gen.nextInt(255) + "," + gen.nextInt(255) + "," + gen.nextInt(255) + ")")));
        }

        ScrollPane root = new ScrollPane(flw);
        root.setMaxSize(500, 500);
        root.setBackground(Background.EMPTY);

        Scene scene = new Scene(root, Color.TRANSPARENT);
        stage.setScene(scene);

        return stage;
    }

This is the output of the code above when Stage.show() is called:

在此处输入图片说明

This stage pops up in a new window but as you see, the background is white and cannot be seen through. I have a feeling the problem the ScrollPane or the FlowPane, because just having StageStyle.TRANSPARENT and a single Square made the square pop up without any white background.

What am I doing wrong? I've already tried doing:

Pane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY)));

It's due to the viewport of your ScrollPane not receiving the transparent background

If you apply the following css:

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

on top of the code you provided, you get the below:

在此处输入图片说明


You will need to add a style sheet to your project and the scene:

Eg If the style sheet is in the src directory

scene.getStylesheets().add("CSS/stylesheet.css");

I prefer to add a CSS directory to allow for more specific style sheets later:

 scene.getStylesheets().add("CSS/stylesheet.css"); 

Don't forget that if you're launching from a jar, you will need to use toExternalForm()

With the style sheet added, you can reduce some Java lines of code used for styling by implementing them with css instead, which should make your code easier to read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM