2016-08-08 22 views
0

我在學習javafx,並且用vbox佈局管理器做了很少的嘗試。代碼似乎是好的,但我想檢查,如果我真的明白它是如何工作的。Javafx:使用佈局管理器進行測試?

下面是代碼:

public class TestShape2 extends Application { 

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

    @Override 
    public void start(Stage primaryStage) throws Exception { 
     Group root = new Group(); 
     Label topLabel = new Label("Top..."); 
     Label topLabel2 = new Label("Top 2..."); 
     Rectangle rect = new Rectangle(); 

     rect.setFill(Color.AQUA); 
     Label bottomLabel = new Label("Bottom..."); 

     VBox vBox = new VBox(); 
     rect.widthProperty().bind(vBox.widthProperty()); 
     rect.heightProperty().bind(vBox.heightProperty()); 

     vBox.getChildren().addAll(topLabel, topLabel2, rect, bottomLabel); 
     /* 
     * Code 1 
     */ 
     root.getChildren().add(vBox); 
     Scene scene = new Scene(root, 300, 300, Color.BLANCHEDALMOND); 

     /* 
     * Code 2 
     */ 
     // Scene scene = new Scene (vBox, 300, 300, Color.BLANCHEDALMOND); 

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

    } 

} 

在「代碼1」:不垂直框中的寬度和高度是那些包含在根屁股的元件的根組是VBOX的父?那麼,vBox不會佔滿整個空間? 在「代碼2」中:因爲我不使用某個根組,因爲場景是vbox的父級,所以vbox的維度將是場景的維度? 我的理解是否正確?

如果這是正確的,我的問題是:將有一個「頂部標籤」,「底部標籤」和矩形,將填補所有的自由空間的代碼是什麼?在代碼2中,我從來沒有看到底部標籤「,因爲它看起來矩形的高度是場景的高度,所以我認爲底部的標籤不在場景中,但是如何解決這個問題?

謝謝大家在理解的JavaFX你的幫助

回答

1

rect.heightProperty().bind(vBox.heightProperty()); 

是你不應該做的事情,它根據其父母的尺寸大小調整Rectangle。然而,有家長的高度取決於大小它的孩子,這種循環依賴導致VBox的行爲不再明確......

在「代碼1」中:vBox的寬度和高度是根元素中包含的元素的寬度和高度,根組是vbox的父元素?

Group的孩子的大小是首選的大小。結合上述問題,您會得到一個不能填充整個寬度/高度的佈局。

在「代碼2」中:因爲我沒有使用某個根組,因此場景是vbox的父級,因此vbox的尺寸將是場景的尺寸?

除了一些不準確的提法晴正確:將Scene沒有任何NodeparentVBoxScene的根,Scene包含VBox

2中的代碼,我從來沒有看到底部的標籤」,因爲它似乎矩形高度爲現場的高度的話,我想的底部標籤是出現場。

那是正確的。

Rectangle不是可調整大小,因此不會有VBox父母很好地工作,以實現所需的行爲。你可以使用'Region'代替然而,這是可以調整大小。灌裝可以使用完成Region「如果需要,可以用邊框替換背景和筆畫。

設置vgrowPriority.ALWAYS告訴VBox總是調整Region,而不是其他的孩子,並設置fillWidthtrue告訴VBox孩子們的大小改變它自己的寬度:

@Override 
public void start(Stage primaryStage) throws Exception { 
    Label topLabel = new Label("Top..."); 
    Label topLabel2 = new Label("Top 2..."); 

    Region rect = new Region(); 
    rect.setBackground(new Background(new BackgroundFill(Color.AQUA, CornerRadii.EMPTY, Insets.EMPTY))); 

    Label bottomLabel = new Label("Bottom..."); 

    VBox vBox = new VBox(); 
    vBox.setFillWidth(true); 

    VBox.setVgrow(rect, Priority.ALWAYS); 

    vBox.getChildren().addAll(topLabel, topLabel2, rect, bottomLabel); 

    Scene scene = new Scene (vBox, 300, 300, Color.BLANCHEDALMOND); 
    primaryStage.setScene(scene); 
    primaryStage.show(); 
}