Tag Archives: background

Transparent background with JavaFX

Something that can be useful is to have a transparent background. For example if one wants to show several components as if they were free-floating windows while keeping them all within the same Stage.

It can be achieved by making each layer transparent (Stage, Scene, Nodes). Here is a simple example that shows how it can be done:

public class TransparentWindow extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        try {
            Label lbl = new Label("LABEL");
            VBox p = new VBox(lbl);

            //make the background of the label white and opaque
            lbl.setStyle("-fx-background-color: rgba(255, 255, 255, 1);");

            //add some borders to visualise the element' locations
            lbl.setBorder(new Border(new BorderStroke(Color.BLUE, BorderStrokeStyle.SOLID, null, null)));
            p.setBorder(new Border(new BorderStroke(Color.RED, BorderStrokeStyle.SOLID, null, null)));

            Scene scene = new Scene(p);
            stage.setScene(scene);

            //this is where the transparency is achieved:
            //the three layers must be made transparent
            //(i)  make the VBox transparent (the 4th parameter is the alpha)
            p.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");
            //(ii) set the scene fill to transparent
            scene.setFill(null);
            //(iii) set the stage background to transparent
            stage.initStyle(TRANSPARENT);

            stage.setWidth(200);
            stage.setHeight(100);
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

And the result looks like this (with my IDE in the background):

Capture

The next step is to add some custom buttons to allow the user to close the window (if you run the example as is you will need to kill the application).

Tagged , , ,