如何使用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);
}
}输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP