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.