有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使滚动窗格适合其在javafx中的父级

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

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

现在我想让滚动窗格的宽度、高度与外部VBox(vb)相同。但我失败了!谁能帮帮我吗


共 (2) 个答案

  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);
    
  2. # 2 楼答案

    首先,不要这样做:

    vb.getChildren().add(vb);
    

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

    其次,使用AnchorPane并设置滚动窗格的约束,如下所示:

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