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.