How to restore original node order after hiding and unhiding nodes from a graph

Questions & Answers

Summary

This article describes how one can restore the original node order of a graph, after hiding and unhiding some of its nodes.
For a better user experience, please go to the integrated documentation viewer to read this article.

Description

When hiding and unhiding nodes from a graph - for example by using the methods described in How to Hide and Unhide Nodes Correctly - the node indices and therefore their order in the graph will be changed. Usually, one should not refer to node indices to bind data to nodes. Instead DataProviders should be used. Have a look at the according section in the yFiles Developper's Guide.
However, if you'll have to restore the original node order for any other reason, this can easily be achieved.
Simply store the node order before hiding the nodes:

private void storeNodeOrder(Graph graph) {
      originalOrder = new HashMap(graph.nodeCount());
      for (NodeCursor nodeCursor = graph.nodes(); nodeCursor.ok(); nodeCursor.next()){
        Node node = nodeCursor.node();
        originalOrder.put(node, Integer.valueOf(node.index()));
      }
    }

and restore this order afterwards:

private void restoreOriginalOrder() {
      Node[] nodes = view.getGraph2D().getNodeArray();
      //sort node array according to original order. 
      //Our own comparator will do this for us referring to the previously saved order
      Arrays.sort(nodes, createNodeOrderComparator());
      //walk through sorted nodes
      for (int i = 0; i < nodes.length; i++) {
        Node node = nodes[i];
        //move every node to last position to restore original node order
        view.getGraph2D().moveToLast(node);
      }
    }

private Comparator createNodeOrderComparator() {
      return new Comparator(){
        public int compare(Object o1, Object o2) {
          if (originalOrder.containsKey(o1) && originalOrder.containsKey(o2)){
            return ((Integer)originalOrder.get(o1)).compareTo((Integer)originalOrder.get(o2));
          } else {
            return 0;
          }
        }
      };
    }

Have a look at the attached sourcecode file for details.

The same method can be used to restore the edge order.

Resources

Categories this article belongs to:
yFiles for Java > yFiles Basic
yFiles for Java > yFiles Layout
yFiles for Java > yFiles Viewer
Applies to:
yFiles for Java 2: 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10, 2.11, 2.12, 2.13, 2.14, 2.15, 2.16, 2.17, 2.18
Keywords:
hiding - unhiding - node - nodes - edge - edges - indices - index - original - order