JavaFX - 子节点重叠父节点(父节点的宽度小于子节点)

问题描述 投票:0回答:1

下面是一个JavaFX应用程序的快速示例,其中棕色区域(父节点)包含两个子节点,一个红色的正方形和一个蓝色的圆形。当我将父节点的宽度缩小到比其子节点小的尺寸时,我希望子节点能够部分可见。然而,事实并非如此,而是子节点完全显示在父节点的区域上。在下面的例子中,有什么想法可以实现吗?

enter image description here

public class Test extends Application {
   public static void main(String[] args) {
       launch(args);
   }

   @Override
   public void start(Stage primaryStage) {
       primaryStage.setTitle("Parent Child Relationship!");
       ParentNode parentNode = new ParentNode();

       StackPane root = new StackPane();
       root.getChildren().add(parentNode);
       primaryStage.setScene(new Scene(root, 300, 250));
       primaryStage.show();
   }
}

class ParentNode extends Region {

    private Rectangle square = new Rectangle();
    private Circle    circle = new Circle();;

   public ParentNode() {
    square.setWidth(40);
        square.setHeight(40);
      square.setFill(Color.RED);

      circle.radiusProperty().bind(square.heightProperty().divide(3));
      circle.centerXProperty().bind(circle.radiusProperty());
      circle.centerYProperty().bind(square.heightProperty().divide(2));
      circle.setFill(Color.BLUE);
      circle.setStroke(Color.LIGHTGRAY);
      getChildren().addAll(square, circle);

      setBackground(new Background(new BackgroundFill(Color.CHOCOLATE, null, null)));
      this.setMaxHeight(100);
      this.setMaxWidth(200);
      this.setMinHeight(0);
      this.setMinWidth(0);

      this.setOnMousePressed((e) -> this.setMaxWidth(20));
    }

}
javafx javafx-8
1个回答
1
投票

我能想到的唯一方法是使用一个矩形作为parentNode的夹子,并将其高度和宽度绑定到parentNode的宽度和高度属性上,这是一个工作示例。

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Parent Child Relationship!");
    ParentNode parentNode = new ParentNode();

    parentNode.maxWidthProperty().bind(primaryStage.widthProperty().subtract(200));

    Rectangle clip = new Rectangle();
    clip.widthProperty().bind(parentNode.widthProperty());
    clip.heightProperty().bind(parentNode.heightProperty());

    parentNode.setClip(clip);
    StackPane root = new StackPane();
    root.getChildren().add(parentNode);
    primaryStage.setScene(new Scene(root, 400, 250));
    primaryStage.show();
}

screenshot2screenshot1

(我将parentNode的宽度绑定到窗口的宽度上,这样你就可以在调整窗口大小的时候看到它的效果了)

© www.soinside.com 2019 - 2024. All rights reserved.