2017-02-10 98 views
0

我想调整ScrollPane,因为它适合其父容器。我测试了这个代码:使ScrollPane适合其父在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(); 
    } 

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

回答

1

首先不这样做:

vb.getChildren().add(vb); 

添加垂直框“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); 
0

首先,你的代码甚至不会编译,因为ScrollPane不能调用getChildren()方法,它保护了ACC ESS。改为使用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);