Andrzej Stempnik Andrzej Stempnik - 6 months ago 62
Java Question

Filling GridPane with numbers/strings

how can I fill my GridPane with integers or strings? I am currently working on Sudoku GUI and can't get it to work. I already know that it's impossible to display it with Java FX Label since it's java.fx.scene.control class. I need to somehow transfer the sudoku values to the corresponding coordinates in the GridPane.

public class Controller {

GridPane sudokuGrid;
private Label[][] label = new Label[9][9];

public void generateButtonClicked(ActionEvent actionEvent) {
SudokuBoard board = new SudokuBoard();
BacktrackingSudokuSolver solver = new BacktrackingSudokuSolver();
solver.fillBoard(0, 0, board);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
label[i][j] = String.valueOf(board.getDigit(i, j).getNum());
sudokuGrid.add(???, i, j);
}
}
}

Answer

Correction

I already know that it's impossible to display it with Java FX Label since it's java.fx.scene.control class.

This is not true, Labels are for displaying values.

Solution

Inside your loop, create a label and place it in your grid:

label[i][j] = new Label(String.valueOf(board.getDigit(i, j).getNum()));
sudokuGrid.add(label[i][j], i, j); 

Answers to additional questions

do you know how to clear the content of the grid after every filling? I get digits on digits with every click of the button

Only add the labels to the the grid once (when you create the grid). Once you have added the labels to the grid, you don't need to add them again. So use the code above to run in a loop and initialize your grid.

After the initialization has completed, just update the text of the labels when you need to. For example, when your generate button is clicked:

for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        label[i][j].setText(
               String.valueOf(board.getDigit(i, j).getNum())
        );
    }
}

If you want to display blank labels, then just set their text to null or the empty string:

for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        label[i][j].setText(null);
    }
}

However I don't create a new grid with every click button, beacuse it's declared in a fxml file

Your FXML controller can have an initialize() method, use it to create the labels in your grid.