Search code examples
layoutjungjung2

Re-layout JUNG graph after adding vertices


Suppose I have a JUNG graph visualized then later wants to add vertices and edges to the graph. I tried to repaint the viewer but the layout for the new vertices are not right:

UndirectedGraph<Integer, String> g = new UndirectedSparseGraph<>();
g.addVertex(1);
g.addVertex(2);
g.addVertex(3);
g.addEdge("A", 1,2);
g.addEdge("B", 2,3);

Layout<Integer, String> layout = new CircleLayout<>(g);
layout.setSize(new Dimension(500, 500));
VisualizationViewer<Integer,String> vv =
        new VisualizationViewer<>(layout);
vv.setPreferredSize(new Dimension(500, 500));

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);

frame.pack();
frame.setVisible(true);

try{Thread.sleep(5000);}
catch(Exception ex){}

g.addVertex((Integer)4);
g.addEdge("C", 1,4);
vv.repaint();

Is there a way to re-layout the graph after adding vertices and edges?


Solution

  • According to Joshua O'Madadhain you need to create a new layout with the updated graph and update the visualization viewer:

    public static void main(String[] args) {
            UndirectedGraph<Integer, String> g = new UndirectedSparseGraph<>();
            g.addVertex(1);
            g.addVertex(2);
            g.addVertex(3);
            g.addEdge("A", 1, 2);
            g.addEdge("B", 2, 3);
    
            Layout<Integer, String> layout = new CircleLayout<>(g);
            layout.setSize(new Dimension(500, 500));
            VisualizationViewer<Integer, String> vv = new VisualizationViewer<>(layout);
            vv.setPreferredSize(new Dimension(500, 500));
    
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(vv);
    
            frame.pack();
            frame.setVisible(true);
    
            try {
                Thread.sleep(2000);
            } catch (Exception ex) {
            }
    
            g.addVertex((Integer) 4);
            g.addEdge("C", 1, 4);
            vv.setGraphLayout(new CircleLayout<>(g));
    
            // vv.repaint();
        }
    

    Reference: JUNG Tree Layout dynamic update