Painting Selected Nodes on Top of Unselected Nodes

Tips & Tricks

Summary

Using the layered painting capabilities of DefaultGraph2DRenderer.

This article was written for an older version. It is only online as a reference for customers using this old version. The information it contains is probably out of date.

The latest information can be found in the yFiles documentation

Description

By default, the rendering of graph elements is performed by the Graph2DRenderer instance registered with a Graph2DView. Class DefaultGraph2DRenderer (the standard Graph2DRenderer) provides optional support for so-called "layered painting," which allows to freely customize the drawing sequence of graph elements by means of the protected callback methods getLayer(Graph2D, Node) and getLayer(Graph2D, Edge), respectively.

The callback methods are used for returning integral layer index values for each node and edge, which determine the drawing sequence of all elements of a graph. The interpretation of the layer index value is that graph elements with a higher index value are painted later, i.e., on top of elements with a lower index value.

The following sample code shows a custom DefaultGraph2DRenderer implementation where the getLayer(Graph2D, Node) callback method returns layer index values so that selected nodes are painted on top of unselected nodes.
Note that layered painting support is disabled by default, i.e., it needs to be enabled for the Graph2DRenderer using the setLayeredPainting method.

// 'view' is of type y.view.Graph2DView.

view.setGraph2DRenderer(new DefaultGraph2DRenderer() {
  // Callback method that is queried for each node of a graph when layer painting
  // is enabled.
  protected int getLayer(Graph2D graph, Node node) {
    // Selected nodes get painted on top of non-selected nodes.
    return (graph.isSelected(node) || isAnyParentNodeSelected(node)) ? 1 : 0;
  }

  /**
   * Determines whether any of the parent nodes of the given node is selected.
   */
  public boolean isAnyParentNodeSelected(Node n) {
    Graph2D graph = (Graph2D)n.getGraph();
    HierarchyManager hierarchy = graph.getHierarchyManager();

    if (hierarchy == null)
      return false;

    boolean result = false;
    Node parent = hierarchy.getParentNode(n);
    while (parent != null) {
      if (graph.isSelected(parent)) {
        result = true;
        break;
      }
      parent = hierarchy.getParentNode(parent);
    }
    return result;
  }
}

// Enable layered painting.
((DefaultGraph2DRenderer)view.getGraph2DRenderer()).setLayeredPainting(true);

Resources

Categories this article belongs to:
yFiles for Java > yFiles Viewer > Displaying and Editing Graphs > View Implementations
Applies to:
yFiles for Java 2: 2.5, 2.6, 2.7, 2.8
Keywords:
rendering - selection - selected - node - on top - Graph2DRenderer - DefaultGraph2DRenderer - drawing - sequence - paint - layer - setLayeredPainting - getLayer - layered - painting