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

时间:2020-06-08 21:03:12

标签: javafx javafx-8

下面是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));
    }

}

1 个答案:

答案 0 :(得分:1)

我能想到的唯一方法是将矩形用作父节点的剪辑并将其高度和宽度绑定到父节点的width和height属性,这是一个有效的示例:

@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();
}

screenshot2 screenshot1

(我将parentNode的宽度限制为窗口宽度,以便在调整窗口大小时可以看到它的工作)

相关问题