JavaFX - 布局面板 HBox



如果我们在应用程序的布局中使用 HBox,则所有节点都将设置在同一水平行中。

名为 HBoxjavafx.scene.layout 包中的类表示 HBox 面板。此类包含五个属性,即 -

  • alignment - 此属性表示 HBox 边界内节点的对齐方式。您可以使用设置方法 setAlignment() 为此属性设置值。

  • fillHeight - 此属性为布尔类型,设置为 true 时,HBox 中的可调整大小的节点将调整为 HBox 的高度。您可以使用设置方法 setFillHeight() 为此属性设置值。

  • spacing - 此属性为双精度类型,表示 HBox 子节点之间的间距。您可以使用设置方法 setSpacing() 为此属性设置值。

此外,此类还提供了一些方法,它们是 -

  • setHgrow() - 设置子节点在 HBox 中包含时的水平增长优先级。此方法接受一个节点和一个优先级值。

  • setMargin() - 使用此方法,您可以为 HBox 设置边距。此方法接受一个节点和一个 Insets 类对象(矩形区域 4 边的内部偏移量集)。

示例

以下程序是 HBox 布局的示例。在这里,我们插入了一个文本字段和两个按钮,播放和停止。这是以 10 的间距完成的,并且每个都有尺寸为 - (10, 10, 10, 10) 的边距。

将此代码保存在名为 HBoxExample.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.HBox;

public class HBoxExample 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 HBox class  
      HBox hbox = new HBox();    
      
      //Setting the space between the nodes of a HBox pane 
      hbox.setSpacing(10);    
      
      //Setting the margin to the nodes 
      hbox.setMargin(textField, new Insets(20, 20, 20, 20)); 
      hbox.setMargin(playButton, new Insets(20, 20, 20, 20)); 
      hbox.setMargin(stopButton, new Insets(20, 20, 20, 20));  
      
      //retrieving the observable list of the HBox 
      ObservableList list = hbox.getChildren();  
      
      //Adding all the nodes to the observable list (HBox) 
      list.addAll(textField, playButton, stopButton);       
      
      //Creating a scene object
      Scene scene = new Scene(hbox);  
      
      //Setting title to the Stage 
      stage.setTitle("Hbox 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 HBoxExample.java 
java HBoxExample.java

执行后,上述程序将生成一个如下图所示的 JavaFX 窗口。

HBox
javafx_layout_panes.htm
广告

© . All rights reserved.