看起来您正在创建9x9=81
“内部”网格窗格,而您应该创建3x3=9
它们。然后你只将每组 9 个中的最后一个添加到板上。你需要类似的东西
GridPane board = new GridPane();
for (int blockColumn = 0; blockColumn < 3 ; blockColumn++) {
for (int blockRow = 0; blockRow < 3; blockRow++) {
GridPane box = new GridPane();
box.setStyle("-fx-background-color: black, -fx-control-inner-background; -fx-background-insets: 0, 2; -fx-padding: 2;");
for (int column = 0; column < 3; column++) {
for (int row = 0 ; row < 3; row++) {
TextField textField = new TextField("0");
textField.setStyle("-fx-pref-width: 2em;");
GridPane.setConstraints(textField, column, row);
box.getChildren().add(textField);
}
}
GridPane.setConstraints(box, blockColumn, blockRow);
board.getChildren().add(box);
}
}
样式设置只是适当地调整文本字段的大小,并在每个“块”(即“内部网格窗格”)周围放置一个黑色边框。
SSCCE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class SudokuBoard extends Application {
@Override
public void start(Stage primaryStage) {
GridPane board = new GridPane();
for (int blockColumn = 0; blockColumn < 3 ; blockColumn++) {
for (int blockRow = 0; blockRow < 3; blockRow++) {
GridPane box = new GridPane();
box.setStyle("-fx-background-color: black, -fx-control-inner-background; -fx-background-insets: 0, 2; -fx-padding: 2;");
for (int column = 0; column < 3; column++) {
for (int row = 0 ; row < 3; row++) {
TextField textField = new TextField("0");
textField.setStyle("-fx-pref-width: 2em;");
GridPane.setConstraints(textField, column, row);
box.getChildren().add(textField);
}
}
GridPane.setConstraints(box, blockColumn, blockRow);
board.getChildren().add(box);
}
}
primaryStage.setScene(new Scene(board));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}