2017-02-10 48 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);