JavaFX - 網格佈局(GridPane)



JavaFX 中的 GridPane 佈局

GridPane 是一種佈局容器,其中所有節點都以形成行和列網格的方式排列。此佈局在建立表單、圖表、媒體庫等方面非常方便。

在 JavaFX 中,名為 GridPane 的類(位於 javafx.scene.layout 包中)表示 GridPane 佈局。使用其預設建構函式例項化此類將在我們的 JavaFX 應用程式中建立一個網格面板佈局。此類提供以下屬性:

  • alignment - 此屬性表示面板的對齊方式,您可以使用 setAlignment() 方法設定此屬性的值。

  • hgap - 此屬性為 double 型別,表示列之間的水平間距。

  • vgap - 此屬性為 double 型別,表示行之間的垂直間距。

  • gridLinesVisible - 此屬性為布林型別。設定為 true 時,面板的網格線將可見。

下表說明了 JavaFX 網格面板中的單元格位置。每個單元格的第一個值表示行,第二個值表示列。

(0, 0) (1, 0) (2, 0)
(0, 1) (1, 1) (2, 1)
(0, 2) (1, 2) (2, 2)

示例

以下程式是網格面板佈局的示例。在此示例中,我們使用網格面板建立一個表單。將此程式碼儲存到名為 GridPaneExample.java 的檔案中。

import javafx.application.Application; 
import javafx.geometry.Insets; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.layout.GridPane; 
import javafx.scene.text.Text; 
import javafx.scene.control.TextField; 
import javafx.stage.Stage; 

public class GridPaneExample extends Application { 
   @Override 
   public void start(Stage stage) {      
      //creating label email 
      Text text1 = new Text("Email");       
      
      //creating label password 
      Text text2 = new Text("Password"); 
	  
      //Creating Text Filed for email        
      TextField textField1 = new TextField();       
      
      //Creating Text Filed for password        
      TextField textField2 = new TextField();  
       
      //Creating Buttons 
      Button button1 = new Button("Submit"); 
      Button button2 = new Button("Clear");  
      
      //Creating a Grid Pane 
      GridPane gridPane = new GridPane();    
      
      //Setting size for the pane  
      gridPane.setMinSize(400, 200); 
       
      //Setting the padding  
      gridPane.setPadding(new Insets(10, 10, 10, 10)); 
      
      //Setting the vertical and horizontal gaps between the columns 
      gridPane.setVgap(5); 
      gridPane.setHgap(5);       
      
      //Setting the Grid alignment 
      gridPane.setAlignment(Pos.CENTER); 
       
      //Arranging all the nodes in the grid 
      gridPane.add(text1, 0, 0); 
      gridPane.add(textField1, 1, 0); 
      gridPane.add(text2, 0, 1);       
      gridPane.add(textField2, 1, 1); 
      gridPane.add(button1, 0, 2); 
      gridPane.add(button2, 1, 2);  
      
      //Creating a scene object 
      Scene scene = new Scene(gridPane, 400, 300);  
      
      //Setting title to the Stage 
      stage.setTitle("Grid Pane Example in JavaFX"); 
         
      //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 --module-path %PATH_TO_FX% --add-modules javafx.controls GridPaneExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls GridPaneExample

輸出

執行上述程式將生成一個 JavaFX 視窗,顯示使用 GridPane 佈局構建的表單。

Grid Pane
廣告