2017-01-09 95 views
0

我有一個ScrollPane裏面有一個窗格。最初該窗格是空的,但我動態地添加了一些ImageViews(垂直排列)。圖像應該調整大小,以便它們適合ScrollPane,而不必水平滾動。這是我做的,到目前爲止:JavaFX ScrollPane不適合寬度

// Pane that is content of ScrollPane and member variable of object 
private MigPane imagesPane = new MigPane("fill"); 
... 
// creating ScrollPane in some method and add to current view 
ScrollPane spImages = new ScrollPane(); 
spImages.setContent(imagesPane); 
spImages.setFitToWidth(true); 
add(spImages, "wrap"); 
... 
// adding images in another method 
getPm().getImages().forEach(image -> { 
     ImageView img = new ImageView(image); 
     img.setPreserveRatio(true); 
     img.fitWidthProperty().bind(imagesPane.widthProperty()); 
     imagesPane.add(img, "wrap"); 
    }); 

,使其適合到滾動的寬度,但爲什麼不調整圖像大小?我錯過了什麼?

回答

0

的圖像適合於僅content的寬度,而不是高度,但如果添加:

scrollPane.setFitToHeight(true); // it will fits to the height also ! 

也:

img.fitHeightProperty().bind(imagesPane.heightProperty()); // to bind the height of the imageview to the content's height 

出於某種原因,我不知道此方法setPreserveRatio(true)導致問題。 我認爲它通過限制其大小來保持圖像的質量,如果刪除它,圖像將正確地適合兩個水平和垂直軸。

setPreserveRatio:指示是否擴展到嵌合邊界框內適合圖像時保持源圖像的高寬比。

編輯:

這將取決於您的佈局(內容)如果你想知道,你將需要例如VBox

VBox container = new VBox(); 
    ScrollPane sp = new ScrollPane(container); 
    sp.setPrefSize(400, 400); 
    sp.setFitToWidth(true); 

    ImageView img = new ImageView(getClass().getResource("imgA.png").toString()); 
    img.setPreserveRatio(true); 
    img.fitWidthProperty().bind(container.widthProperty()); 

    ImageView img2 = new ImageView(getClass().getResource("imgB.png").toString()); 
    img2.setPreserveRatio(true); 
    img2.fitWidthProperty().bind(container.widthProperty()); 

    container.getChildren().addAll(img,img2); 

祝你好運!

+0

這不是我想要的(也不工作)。我希望滾動窗格的內容僅適用於寬度,所以我可以垂直滾動,但不必水平滾動。 – LPrc

+0

我根據上面的評論編輯了我的答案! –