javagraphjgraphtjgraphxjgraph

How to get coordinates of a mxCell?


I need to get the coordinates (x,y) of a mxCell that i find by his Id, but when i call getGeometry() on it, it gives me null and after i get NullPointerException.

private double getX(String node){
    mxCell cell = (mxCell) ((mxGraphModel)map.getGraph().getModel()).getCell(node);
    mxGeometry geo = cell.getGeometry();//this line give me the null value
    double x = geo.getX();//NullPointerException
    return x;
}

map is the mxGraphComponent that contains all the graph.

What am i missing?


Solution

  • I assume your String node argument should be mapped to the cell's id.

    Basically, you select all cells, get them and iterate over them. Since nearly everything in JGraph is Object, you need some casts.

    private double getXForCell(String id) {
        double res = -1;
        graph.clearSelection();
        graph.selectAll();
        Object[] cells = graph.getSelectionCells();
        for (Object object : cells) {
            mxCell cell = (mxCell) object;
            if (id.equals(cell.getId())) {
                res = cell.getGeometry().getX();
            }
        }
        graph.clearSelection();
        return res;
    }
    

    You might as well check if cell.isVertex() before calling getGeometry(), since its implemented differently on edges.

    Edit: Followed your approach and the following works for me, too. Seems like you need the extra cast (mxCell).

    mxGraphModel graphModel = (mxGraphModel) graph.getModel();
    return ((mxCell) graphModel.getCell(id)).getGeometry().getX();