JavaFX - VBox 佈局



如果我們在應用程式中使用 VBox 作為佈局,所有節點將設定在一個垂直列中。

名為 VBox,位於包 javafx.scene.layout 中的類代表 VBox 面板。此類包含五個屬性,它們是:

  • alignment - 此屬性表示 VBox 邊界內節點的對齊方式。可以使用設定方法 setAlignment() 為此屬性設定值。

  • fillHeight - 此屬性為布林型別,設定為 true 時,VBox 中的可調整大小的節點將調整為 VBox 的高度。可以使用設定方法 setFillHeight() 為此屬性設定值。

  • spacing - 此屬性為雙精度型別,它表示 VBox 子節點之間的間距。可以使用設定方法 setSpacing() 為此屬性設定值。

除此之外,此類還提供以下方法:

  • setVgrow() - 設定 VBox 包含子節點時的垂直增長優先順序。此方法接受一個節點和一個優先順序值。

  • setMargin() - 使用此方法,可以為 VBox 設定邊距。此方法接受一個節點和一個 Insets 類物件(矩形區域四個邊的內側偏移量集合)。

示例

下面的程式是 VBox 佈局的示例。在這個例子中,我們插入了一個文字欄位和兩個按鈕,播放和停止。間距為 10,每個都有 (10, 10, 10, 10) 尺寸的邊距。

將此程式碼儲存到名為 VBoxExample.java 的檔案中。

import javafx.application.Application; 
import javafx.collections.ObservableList; 
import javafx.geometry.Insets; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.TextField; 
import javafx.stage.Stage; 
import javafx.scene.layout.VBox; 
         
public class VBoxExample extends Application { 
   @Override 
   public void start(Stage stage) {       
      //creating a text field 
      TextField textField = new TextField();       
      
      //Creating the play button 
      Button playButton = new Button("Play");
	   
      //Creating the stop button 
      Button stopButton = new Button("stop"); 
      
      //Instantiating the VBox class  
      VBox vBox = new VBox();   
      
      //Setting the space between the nodes of a VBox pane 
      vBox.setSpacing(10);   
      
      //Setting the margin to the nodes 
      vBox.setMargin(textField, new Insets(20, 20, 20, 20));  
      vBox.setMargin(playButton, new Insets(20, 20, 20, 20)); 
      vBox.setMargin(stopButton, new Insets(20, 20, 20, 20));  
      
      //retrieving the observable list of the VBox 
      ObservableList list = vBox.getChildren(); 
      
      //Adding all the nodes to the observable list 
      list.addAll(textField, playButton, stopButton);       
      
      //Creating a scene object 
      Scene scene = new Scene(vBox);  
      
      //Setting title to the Stage 
      stage.setTitle("Vbox Example"); 
         
      //Adding scene to the stage 
      stage.setScene(scene); 
         
      //Displaying the contents of the stage 
      stage.show(); 
   } 
   public static void main(String args[]){ 
      launch(args); 
   } 
}

使用以下命令從命令提示符編譯並執行儲存的 java 檔案。

javac VBoxExample.java 
java VBoxExample.java

執行後,上述程式將生成如下所示的 JavaFX 視窗。

VBox
javafx_layout_panes.htm
廣告
© . All rights reserved.