【问题标题】:Make ScrollPane fit to its parent in javafx使 ScrollPane 适合其在 javafx 中的父级
【发布时间】:2017-02-11 06:53:28
【问题描述】:

我想调整 ScrollPane 的大小,使其适合其父容器。我测试了这段代码:

    @Override
    public void start(Stage stage) throws Exception {

        VBox vb = new VBox();
        vb.setPrefSize(600, 600);
        vb.setMaxSize(600, 600);

        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setFitToHeight(false);
        scrollPane.setFitToWidth(false);

        scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
        scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);

        VBox vb2 = new VBox();

        vb.getChildren().add(scrollPane);
        scrollPane.getChildren().add(vb2);

        Scene scene = new Scene(vb);

        stage.setScene(scene);
        stage.show();
    }

现在我想让scrollPane 的宽度、高度与外部VBox(vb) 相同。但是我失败了!有人可以帮帮我吗?

【问题讨论】:

    标签: java javafx


    【解决方案1】:

    首先不要那样做:

    vb.getChildren().add(vb);
    

    将 VBox 'vb' 添加到自身会导致异常并且没有任何意义:D

    第二次使用 AnchorPane 并为 ScrollPane 设置约束,如下所示:

    //Create a new AnchorPane
    AnchorPane anchorPane = new AnchorPane();
    
    //Put the AnchorPane inside the VBox
    vb.getChildren().add(anchorPane);
    
    //Fill the AnchorPane with the ScrollPane and set the Anchors to 0.0
    //That way the ScrollPane will take the full size of the Parent of
    //the AnchorPane (here the VBox)
    anchorPane.getChildren().add(scrollPane);
    AnchorPane.setTopAnchor(scrollPane, 0.0);
    AnchorPane.setBottomAnchor(scrollPane, 0.0);
    AnchorPane.setLeftAnchor(scrollPane, 0.0);
    AnchorPane.setRightAnchor(scrollPane, 0.0);
    //Add content ScrollPane
    scrollPane.getChildren().add(vb2);
    

    【讨论】:

      【解决方案2】:

      起初,您的代码甚至无法编译,因为ScrollPane 无法调用getChildren() 方法,它具有受保护的访问权限。请改用scrollPane.setContent(vb2);

      第二 - 调用vb.getChildren().add(vb); 没有任何意义,因为您正试图将Node 添加到自己。它会抛出java.lang.IllegalArgumentException: Children: cycle detected:

      接下来,如果您希望 ScrollPane 适合 VBox 大小,请使用以下代码:

      vb.getChildren().add(scrollPane);
      VBox.setVgrow(scrollPane, Priority.ALWAYS);
      scrollPane.setMaxWidth(Double.MAX_VALUE);
      
      scrollPane.setContent(vb2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-31
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-10
        • 1970-01-01
        • 2013-10-20
        相关资源
        最近更新 更多