JavaFX - 網格佈局 GridPane



如果我們在應用程式中使用 GridPane,則新增到其中的所有節點都將以形成行和列網格的方式排列。這種佈局在使用 JavaFX 建立表單時非常方便。

名為 GridPane 的類(位於 javafx.scene.layout 包中)表示 GridPane。此類提供了十一個屬性,它們是:

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

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

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

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

以下是 JavaFX GridPane 中的單元格位置:

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

示例

以下程式是 GridPane 佈局的示例。在這個例子中,我們使用 GridPane 建立一個表單。

將此程式碼儲存在名為 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);  
      
      //Setting title to the Stage 
      stage.setTitle("Grid Pane 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 GridPaneExample.java 
java GridPaneExample

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

Grid Pane
javafx_layout_panes.htm
廣告
© . All rights reserved.