2016-08-15 73 views
0

我正在用ScrollPane編寫GUI應用程序,但在調整大小時遇到​​了一些問題。我提取在下面的示例中的基本代碼:JavaFX ScrollPane [setPrefSize,setMinSize,setMaxSize]不起作用

import javafx.application.Application; 
import javafx.geometry.Bounds; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.stage.Stage; 
import javafx.scene.layout.VBox; 
import javafx.scene.control.ScrollPane; 

public class JavaFXExample extends Application { 

    final int width = 300; 
    final int height = 300; 

    @Override 
    public void start(Stage primaryStage) { 

     Button b = new Button("This should be at the bottom!"); 

     //this vbox goes inside the scrollpane 
     VBox boxInScrollPane = new VBox(10); 
     boxInScrollPane.setAlignment(Pos.BOTTOM_CENTER); 
     boxInScrollPane.getChildren().add(b); 

     //main content 
     ScrollPane scrollPane = new ScrollPane(); 
     scrollPane.setContent(boxInScrollPane); 
     scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); 
     scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); 

     //Doesn't do anything! 
     scrollPane.setPrefSize(100, 100); 
     scrollPane.setMaxSize(100, 100); 
     scrollPane.setMinSize(100, 100); 

     Scene scene = new Scene(scrollPane, width, height); 

     primaryStage.setScene(scene); 
     primaryStage.show(); 


     //set size of boxInScrollPane to be equal to the viewport 
     Bounds viewportBounds = scrollPane.getViewportBounds(); 
     double innerWidth = viewportBounds.getMaxX() - viewportBounds.getMinX(); 
     double innerHeight = viewportBounds.getMaxY() - viewportBounds.getMinY(); 
     System.out.println(innerWidth + " " + innerHeight); 
     boxInScrollPane.setPrefSize(innerWidth, innerHeight); 

    } 

    public static void main(String[] args) { 
     launch(args); 
    } 

} 

所以我有一個窗口,其中包含一個ScrollPane,其中包含一個垂直框,其中包含一個按鈕。這裏的例子中,我調整了一個300x300px窗口中的滾動窗格大小爲100x100px,是任意的。重要的是,當我運行這段代碼時,我會看到一個可以填滿整個窗口的滾動窗格!這裏是我的輸出:

這是怎麼回事?

回答

1

無論最小/最大/最大大小如何,場景的根大小都會填滿整個場景。如果你想讓ScrollPane保持100像素寬和100像素高,將其包裝在另一個容器中(幾乎任何容器都可以);那麼容器將被調整,但ScrollPane將尊重它的配置尺寸:

Scene scene = new Scene(new StackPane(scrollPane), width, height); 

缺省情況下StackPane中心的內容,因此這導致

enter image description here

1

解決方案:

Pane pane = new Pane(scrollPane); 
Scene scene = new Scene(pane, width, height); 

primaryStage.setScene(scene); 

primaryStage.show(); 

從場景constuctor DOC:

創建場景特定根節點具有特定的大小。

將ScrollPane設置爲根節點將使其在構造函​​數中調整爲給定大小,因此以前的設置將不起作用。

解決方案將是製作一個簡單的窗格,將調整大小,以便ScrollPane將按照他自己的規則。