如何使用JavaFX建立網格窗格?


建立應用程式所需的所有節點後,可以使用佈局來排列它們。佈局是計算物件在給定空間中位置的過程。JavaFX在javafx.scene.layout包中提供了各種佈局。

網格窗格

在此佈局中,您可以將節點排列為行和列的網格。您可以透過例項化javafx.scene.layout.GridPane類在應用程式中建立網格窗格。

您可以使用setRowIndex()setColumnIndex()方法設定窗格中節點的位置。

此類具有以下屬性:

  • alignment −(Pos) 指定網格在窗格尺寸內的位置。

  • gridLinesVisible − (boolean) 指定是否顯示突出顯示窗格行和列的線條。

  • hgap − (double) 指定網格列之間的水平間距。

  • vgap − (double) 指定網格行之間的垂直間距。

您可以透過使用其各自的setter方法設定這些屬性的值來自定義網格的外觀。

要向此窗格新增節點,您可以將它們作為建構函式的引數傳遞,或者將其新增到窗格的可觀察列表中,如下所示:

getChildren().addAll();

示例

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class GridLayoutExample extends Application {
   public void start(Stage stage) {
      //Creating labels
      Text text1 = new Text("Email");
      Text text2 = new Text("Password");
      //Creating text and password fields
      TextField textField1 = new TextField();
      PasswordField textField2 = new PasswordField();
      //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);
      //Setting the stage
      Scene scene = new Scene(gridPane, 595, 200, Color.BEIGE);
      stage.setTitle("Grid Layout");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於:2020年5月19日

616 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告