使ScrollPane适合javafx中的父级

时间:2017-02-10 19:05:42

标签: java javafx

我想调整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)相同。但我失败了!请有人帮帮我吗?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

首先,您的代码甚至不会编译,因为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);