您所要做的就是设置网格约束以满足您的需求。为此,将其Labels
放入 a GridRow
(不需要 a StackPane
)并将其 vAlignment 和 hAlignment 设置为 Center。然后将标签的 vGrow 和 hGrow 设置为Priority.ALWAYS
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
GridPane gridPane = createMainGrid(2, 2);
gridPane.setAlignment(Pos.CENTER);
gridPane.setHgap(10);
gridPane.setVgap(10);
Scene scene = new Scene(gridPane);
primaryStage.setScene(scene);
primaryStage.show();
}
private GridPane createMainGrid(int rows, int columns) {
GridPane grid = new GridPane();
for (int colIdx = 0; colIdx < columns; colIdx++) {
for (int rowIdx = 0; rowIdx < rows; rowIdx++) {
GridPane innerGrid = createGrid(4, 4);
grid.add(innerGrid, colIdx, rowIdx);
GridPane.setConstraints(innerGrid, colIdx, rowIdx, 1, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
}
}
return grid;
}
private GridPane createGrid(int rows, int columns) {
GridPane grid = new GridPane();
Random random = new Random();
for (int colIdx = 0; colIdx < columns; colIdx++) {
for (int rowIdx = 0; rowIdx < rows; rowIdx++) {
Label label = new Label(String.valueOf(random.nextInt(rows * columns)));
label.setMinSize(30, 30);
label.setAlignment(Pos.CENTER);
grid.add(label, colIdx, rowIdx);
GridPane.setConstraints(label, colIdx, rowIdx, 1, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
}
}
return grid;
}
public static void main(String[] args) {
launch(args);
}
}