添加顶点后重新布局JUNG图

时间:2015-11-05 23:18:10

标签: layout jung jung2

假设我有一个可视化的JUNG图,然后想要向图中添加顶点和边。我试图重新绘制查看器,但新顶点的布局不正确:

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();

有没有办法在添加顶点和边后重新布局图形?

1 个答案:

答案 0 :(得分:1)

根据Joshua O'Madadhain,您需要使用更新的图形创建新布局并更新可视化查看器:

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();
    }

参考:JUNG Tree Layout dynamic update