我想调整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)相同。但是我失败了!有人可以帮我吗?
最佳答案
首先不要这样做:
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);
关于java - 使ScrollPane适合其在JavaFX中的父级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42166865/