How to layout a graph in a separate thread |
| Applies to: yFiles 2.4, yFiles 2.3 |
Type: Questions & Answers
Categories this article belongs to:
| yFiles for Java | > yFiles Layout | > Automatic Graph Layout |
Explains how to invoke a layout algorithm from within a desktop application so that the GUI stays responsive
while the layout is being calculated.
Since the calculation of a graph layout may take a long time it is desireable to invoke a layout algorithm within a separate thread so that the GUI of the application stays responsive. Ensuring that the graph can be properly displayed while it is being laid out requires that the layout algorithm works on a copy of the graph. The layout result needs to be applied to the original graph in a synchronized manner.
the following code represents an action event code that invokes a layout algorithm wthin a separate thread.
class ThreadedLayoutAction extends AbstractAction { boolean layoutMorphingEnabled = true; public ThreadedLayoutAction() { super("Threaded Layout"); } public void actionPerformed(ActionEvent ev) { final OrganicLayouter layouter = new OrganicLayouter(); //copy graph in AWT thread. final CopiedLayoutGraph cGraph = new CopiedLayoutGraph(view.getGraph2D()); //calculate layout on a copy of the original graph //within a separate thread. final Thread thread = new Thread() { public void run() { layouter.doLayout(cGraph); //assing calculated layout to original graph within //the AWT thread. SwingUtilities.invokeLater(new Runnable() { public void run() { if(layoutMorphingEnabled) { //perform animated morphing on layout result GraphLayout gl = cGraph.getLayoutForOriginalGraph(); new LayoutMorpher(view, gl).execute(); } else { //assign layout and display result cGraph.commitLayoutToOriginalGraph(); view.fitContent(); view.updateView(); } } }); } }; //assign minimum priority to the thread so that the //GUI remains responsive thread.setPriority(Thread.MIN_PRIORITY); //start the thread thread.start(); } } |
| Warning |
| When applying the calculated layout to the original graph it is important that no nodes or edges have been added or removed from the graph during the layout process |
Attached is an executable demo program that makes use of the ThreadedLayoutAction. It extends demo.view.ViewActionDemo and should be placed in the yFiles demo package demo.view to function properly.
| Resources: |
| Keywords: | thread - background - responsive GUI - layout invokation |


