Search code examples
javajavafxtextfieldgridpane

Javafx get text from textfields in gridpane


for a project I'm working on, I have to display the values of a matrix in a screen. I chose to do this by using text fields in a gridpane as following code indicates:

for(int row = 0; row < length; row++){
        for(int column = 0; column < width; column++){
            // Create a new TextField in each Iteration
            TextField tf = new TextField();
            tf.setPrefHeight(50);
            tf.setPrefWidth(50);
            tf.setAlignment(Pos.CENTER);
            tf.setEditable(true);
            tf.setText(String.valueOf(this.getElement(row, column)));

            // Iterate the Index using the loops
            setRowIndex(tf,row);
            setColumnIndex(tf,column);    
            table.getChildren().add(tf);
        }
    }

If I change the values inside that screen for the text fields, I want to be able to save them. In order to do that, I have to be able to get the text from the text fields. I tried following code, but the iteration over the elements of the table are defined as Nodes, and therefor don't have a .getText() method.

OkButton.setOnAction(new EventHandler<ActionEvent>(){
        @Override
        public void handle (ActionEvent event){
           for (Node nd:table.getChildren()){
               //Code goes here but Node does not have .getText() method
           }

            Stage stage = (Stage) OkButton.getScene().getWindow();
            stage.close();
        }
    });

Does anyone know how to get those values?

Thanks a lot!


Solution

  • Assuming that table is of type GridPane, you should add your TextFields like this:

    table.add(tf, column, row);
    

    For accessing an element, when it's col and row indices are known there is no easy way:

    public Node getNodeByRowColumnIndex(final int row,final int column,GridPane gridPane) {
        Node result = null;
        ObservableList<Node> childrens = gridPane.getChildren();
        for(Node node : childrens) {
            if(gridPane.getRowIndex(node) == row && gridPane.getColumnIndex(node) == column) {
                result = node;
                break;
            }
        }
        return result;
    }
    

    See also the answer to JavaFX: Get Node by row and column.