I am a beginner in using JavaFX and have to create an interactive Sudoku board for a final project. My plan was to add nine 3 by 3 GridPanes to a 3 by 3 GridPane (to make the nice looking board with outlined boxes) but can't seem to do it as I have.
Here is an excerpt from my blankBoard() creation method. board and box are predefined as global GridPane variables:
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
for (int row1 = 0; row1 < 3; row1++) {
for (int col1 = 0; col1 < 3; col1++) {
text = new TextField("0");
box = new GridPane();
GridPane.setConstraints(text, col1, row1);
box.getChildren().addAll(text);
}
}
GridPane.setConstraints(box, col, row);
board.getChildren().addAll(box);
}
}
All this gives me is a 3 by 3 GridPane as such: GridPane
Is there any other way to do this or simply add borders between just some columns and rows in a 9 by 9 GridPane?
It looks like you are creating 9x9=81
"inner" grid panes, when you should be creating 3x3=9
of them. And then you are adding only the last of each set of 9 of them to the board. You need something like
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);
}
}
The style settings just size the text fields appropriately and put a black border around each of the "blocks" (i.e. "inner grid panes").
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);
}
}