Search code examples
javafxtextfieldgridpane

Refering to a textfield in Gridpane


alright. So to give ya'll some background info: I'm programming a sudoku, haven't worked too much with GUI but done much research.

I've created a 2 for loops creating a 9x9 Gridpane filled with textfields with the following code

GridPane grid = new GridPane();

for(int x =0; x < 9; x++){
    for(int y= 0; y < 9; y++){
        TextField textField = new TextField("0");
        textField.setStyle("-fx-pref-width: 2em;");
        GridPane.setConstraints(textField, y, x);
        grid.getChildren().add(textField);
    }
}

Now what I do is to have a clear way of taking - for example the coordinate [2][5] to return to an 2d array and compare to the answer sheet. My problem is to specify a coordinate in my gridpane.

Best regards.


Solution

  • Put the text fields in an array:

    GridPane grid = new GridPane();
    TextField[][] textFields = new TextField[9][9] ;
    
    for(int x =0; x < 9; x++){
        for(int y= 0; y < 9; y++){
            TextField textField = new TextField("0");
            textField.setStyle("-fx-pref-width: 2em;");
            GridPane.setConstraints(textField, y, x);
            grid.getChildren().add(textField);
            textFields[x][y]=textField ;
        }
    }
    

    Then you can access any element (x,y) with textFields[x][y].getText().