javafx GridPane retrieve specific Cell content

旧时模样 提交于 2019-11-27 15:30:31

Well I guess if there is no solution to get a specific node from gridpane by is column and row index, I have a function to do that,

private Node getNodeFromGridPane(GridPane gridPane, int col, int row) {
    for (Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) {
            return node;
        }
    }
    return null;
}

Assuming you have an 8x8 girdPane where i is the rows and j is the column, you can write:

myGridPane.getChildren().get(i*8+j)

The return type is an object, so you will have to cast it, in my case it's:

(StackPane) (myGridPane.getChildren().get(i*8+j))

You can add a list that contains every child of the gridpane and each child's parent must have two integers row and column, therefor you'll just have to go through that list and see if it has the right coordinates ! (You should propably add a new class so you can store those coordinates), here is a minimal example of my solution

import java.util.ArrayList;
import java.util.List;

import javafx.scene.Node;
import javafx.scene.layout.GridPane;

public class SpecialGridPane extends GridPane {
    List<NodeParent> list = new ArrayList<>();

    public void addChild(int row, int column, Node node) {
        list.add(new NodeParent(row, column, node));
        setConstraints(node, column, row);
        getChildren().add(node);
    }

    public Node getChild(int row, int column) {
        for (NodeParent node : list) {
            if (node.getRow() == row && node.getColumn() == column)
                return node.getNode();
        }
        return null;
    }
}

class NodeParent {
    private int row;
    private int column;
    private Node node;

    public NodeParent(int row, int column, Node node) {
        this.row = row;
        this.column = column;
        this.node = node;
    }

    public int getRow() {
        return row;
    }

    public int getColumn() {
        return column;
    }

    public Node getNode() {
        return node;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!