简体   繁体   English

Javafx从gridpane中的文本字段获取文本

[英]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. 我尝试了以下代码,但是将表元素上的迭代定义为Nodes,因此没有.getText()方法。

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! 非常感谢!

Assuming that table is of type GridPane , you should add your TextField s like this: 假设table的类型为GridPane ,则应这样添加TextField

table.add(tf, column, row);

For accessing an element, when it's col and row indices are known there is no easy way: 对于访问元素,当知道col和row索引时,没有简单的方法:

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 . 另请参见JavaFX的答案:按行和列获取Node

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM