多读书多实践,勤思考善领悟

JavaFX Layout GridPane(布局网格面板)

本文于1660天之前发表,文中内容可能已经过时。

如果我们在应用程序中使用网格窗格,则添加到其中的所有节点的排列方式都会形成行和列的网格。使用JavaFX创建表单时,此布局非常方便。

javafx.scene.layout的名为GridPane的类表示GridPane。这个类提供了11个属性,它们是 -

  • alignment - 此属性表示窗格的对齐方式,您可以使用setAlignment()方法设置此属性的值。
  • hgap - 此属性的类型为double,它表示列之间的水平间隙。
  • vgap - 此属性的类型为double,它表示行之间的垂直间距。
  • gridLinesVisible - 此属性是布尔类型。如果为true,则窗格的行被设置为可见。

以下是JavaFX网格面板中的单元格位置 -

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

以下程序是网格窗格布局的示例。在这里,我们使用网格窗格创建一个表单。

将此代码保存在名为GridPaneExample.java的文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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文件。

1
2
javac GridPaneExample.java 
java GridPaneExample

执行时,上面的程序生成一个JavaFX窗口,如下所示。

网格窗格