Hatefiend Hatefiend - 5 months ago 22
Java Question

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:

enter image description here

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)));

Answer

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:

enter image description here