首页 > 解决方案 > JavaFX - Child Nodes Overlapping Parent Node (Parent's width smaller than children)

问题描述

Below there is a quick sample of a JavaFX application where the brown region (parent node) contains two child nodes, a red square and a blue circle. When I am reducing the width of the parent node to a size smaller than those of its children, I was expecting the child nodes to be partially visible. However, this is not the case but instead the child nodes are shown fully over parent's region. Any ideas on how to achieve that on the below example?

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

}

标签: javafxjavafx-8

解决方案


The only way i can think of, would be using a rectangle as the clip for the parentNode and binding its height and width to the parentNode's width and height properties, here is a working example:

@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

(i bound the parentNode's width to the windows width just so you see it working while you resize the window)


推荐阅读