JavaFX:按行和列获取节点

Geo*_*iev 26 java javafx

如果我知道它的位置(行和列)或从gridPane获取节点的任何其他方式,有没有办法从gridPane获取特定节点?

inv*_*ant 35

我看不出有任何直接的API来获取由行列索引节点,但可以使用getChildrenAPI从Pane,并getRowIndex(Node child)getColumnIndex(Node child)来自GridPane

//Gets the list of children of this Parent. 
public ObservableList<Node> getChildren() 
//Returns the child's column index constraint if set
public static java.lang.Integer getColumnIndex(Node child)
//Returns the child's row index constraint if set.
public static java.lang.Integer getRowIndex(Node child)
Run Code Online (Sandbox Code Playgroud)

以下是从中获取Node行和列索引的示例代码GridPane

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;
}
Run Code Online (Sandbox Code Playgroud)

重要更新: getRowIndex()getColumnIndex()现在的静态方法和应改为GridPane.getRowIndex(node)GridPane.getColumnIndex(node).

  • 我认为,如果在节点上设置了这样的约束,则方法getRowIndex()和getColumnIndex()仅返回一个值,即不能保证它们将返回列或行索引。 (2认同)
  • 确保设置了约束。Scenebuilder喜欢将0设置为未设置,并将字段设为空。因此,请在fxml文件中手动设置约束。例如&lt;Canvas GridPane.columnIndex =” 0” GidPan.rowIndex =” 0”&gt;。另外,由于不能保证从getRowIndex / getColumnIndex返回非null值,因此应使用Integer对象,并在if语句中检查null。例如if(null!= nodeRow &amp;&amp; null!= nodeCol ... (2认同)