2013-07-10 124 views
38

我有BorderPaneScrollPane爲中心元素。它會自動調整大小以填滿屏幕。在ScrollPane內部是一個HBox,它沒有內容,但是是一個拖放目標。因此我想要它填寫其父母ScrollPane如何調整JavaFX ScrollPane內容的大小以適合當前的大小

這樣做的首選方法是什麼?

我已經試過到目前爲止被重寫ScrollPane.resize(...)方法來調整HBox但似乎相當複雜的,非正統。

編輯:要添加一些有用的代碼到這一點,這是我怎麼能解決該問題,但我相信,必須有一些更好的方式來做到這一點:部分從這裏取

@Override 
public void resize(double width, double height) { 
    super.resize(width, height); 

    double scrollBarHeight = 2; 
    double scrollBarWidth = 2; 

    for (final Node node : lookupAll(".scroll-bar")) { 
     if (node instanceof ScrollBar) { 
      ScrollBar sb = (ScrollBar) node; 
      if (sb.getOrientation() == Orientation.HORIZONTAL) { 
       System.out.println("horizontal scrollbar visible = " + sb.isVisible()); 
       System.out.println("width = " + sb.getWidth()); 
       System.out.println("height = " + sb.getHeight()); 
       if(sb.isVisible()){ 
        scrollBarHeight = sb.getHeight(); 
       } 
      } 
      if (sb.getOrientation() == Orientation.VERTICAL) { 
       System.out.println("vertical scrollbar visible = " + sb.isVisible()); 
       System.out.println("width = " + sb.getWidth()); 
       System.out.println("height = " + sb.getHeight()); 
       if(sb.isVisible()){ 
        scrollBarWidth = sb.getWidth(); 
       } 
      } 
     } 
    } 

    hBox.setPrefSize(width-scrollBarWidth, height-scrollBarHeight); 
} 

代碼: How to access the Scrollbars of a ScrollPane

+0

這沒關係,我只是把hgrow和vgrow有時,它現在作品 – user7867610

回答

62

嘗試

ScrollPane scrollPane = new ScrollPane(); 
scrollPane.setFitToHeight(true); 
scrollPane.setFitToWidth(true); 

而不重寫resize()方法。

+1

就像我想的那樣,必須有一種我沒有發現的明顯方式。非常感謝您的回答! – Lennert

+0

xml中setFitToHeight和setFitToWidth的訪問方法是什麼? – Andrew121007

+6

@ Andrew121007它是'' –

17

通過XMLCSS設置fitToHeightfitToWidth屬性:

FXML:

<ScrollPane fx:id="myScrollPane" fitToHeight="true" fitToWidth="true" /> 

CSS:

+0

我喜歡使用ScrollPane而不是像.my-scroll-pane這樣的東西來使整個事情自動化,需要FXML更改..應該可能是默認值。 – User

+0

@Manius這是真的,但你應該小心,你做它具體,否則所有的滾動窗格行爲是相同的,可能你不想這樣做。 – NDY

+0

我想添加該選項在Scene Builder中可用。在'佈局' - >'特定'(從頂部開始第二個) - >適合寬度/高度的任何滾動窗格中。花了我一段時間找到希望這有助於某人。 –

相關問題