How to implement a transparent Pane with non-transparent children?

前端 未结 1 549
滥情空心
滥情空心 2020-11-30 10:16

How can i implement a transparent panel with non-transparent children in JavaFX 2? The effect i want to achieve is for example applied to menus in Blender:

相关标签:
1条回答
  • 2020-11-30 10:39

    Set the background of your pane to a color with an alpha component. You can use a stylesheet or an inline style for this.

    For example, if your pane was named glass, then the following will give it a rounded, translucent cyan background:

    glass.setStyle("-fx-background-color: rgba(0, 100, 100, 0.5); -fx-background-radius: 10;");
    

    You could also accomplish similar effects using blends, stackpanes or groups of items with the opacity set for items at the back of the stackpane or group.

    Here is an executable example using the css background method.

    import javafx.application.Application;
    import javafx.geometry.Pos;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.image.*;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    
    public class TranslucentPane extends Application {
      @Override public void start(final Stage stage) throws Exception {
        final ImageView imageView = new ImageView(
          new Image("https://upload.wikimedia.org/wikipedia/commons/b/b7/Idylls_of_the_King_3.jpg")
        );
        imageView.setFitHeight(300);
        imageView.setFitWidth(228);
    
        final Label label = new Label("The Once\nand\nFuture King");
        label.setStyle("-fx-text-fill: goldenrod; -fx-font: italic 20 \"serif\"; -fx-padding: 0 0 20 0; -fx-text-alignment: center");
    
        StackPane glass = new StackPane();
        StackPane.setAlignment(label, Pos.BOTTOM_CENTER);
        glass.getChildren().addAll(label);
        glass.setStyle("-fx-background-color: rgba(0, 100, 100, 0.5); -fx-background-radius: 10;");
        glass.setMaxWidth(imageView.getFitWidth() - 40);
        glass.setMaxHeight(imageView.getFitHeight() - 40);
    
        final StackPane layout = new StackPane();
        layout.getChildren().addAll(imageView, glass);
        layout.setStyle("-fx-background-color: silver; -fx-padding: 10;");
        stage.setScene(new Scene(layout));
        stage.show();
      }
    
      public static void main(String[] args) { launch(args); }
    }
    

    Sample program output:

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