Prevent cycles in the diagram

A frequent requirement for many kinds of diagrams is to keep their underlying graphs acyclic. If your application lets users draw diagrams interactively, you could prevent forming a cycle by rejecting new link between a pair of nodes that are already connected by a path.

Say there is a path node1 -> node2 -> … -> nodeN; letting user draw a link from nodeN to node1 would result in a cycle. We can prevent that by handling the LinkCreating validation event and looking for path using PathFinder class:

diagram.addDiagramListener(new DiagramAdapter()
{
    @Override
    public void linkCreating(LinkValidationEvent e)
    {
        PathFinder pathFinder = new PathFinder(diagram);
        Path path = pathFinder.findShortestPath(
            e.getDestination(), e.getOrigin());
        e.setCancel(path != null);
    }
});

Note that if you allow users modify links, you’d have to apply that logic from LinkModifying event as well.

By default, the control also allows drawing self-loop links. Disable them by setting diagram’s AllowSelfLoops property to false:

diagram.setAllowSelfLoops(false);

Code above demonstrates MindFusion’s Java diagramming API, but same events and types exist in our .NET and JavaScript libraries.

Enjoy!