Search code examples
javaswingjpanelgraphstream

All the nodes gathered at one place - GraphStream - JAVA


I am working on GraphStream Library for java. But I am facing a problem here. When I try to get the nodes from the DB Table it shows the data along with edges on JPanel but at first, when program starts, it gathered all the nodes at one place like this image. So, I have to drag all the nodes. Why this is happening ? Any little hint would be appreciated.

enter image description here

Here is my code :

public class GraphExplore {
    static Connection conn2;
    static String result, result2;
    static int totalRows, i;

    public static void main(String args[]) throws SQLException {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    showData();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private static void showData() throws SQLException {

        JFrame frame = new JFrame();
        frame.setBounds(30, 50, 1300, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new GridLayout()){
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(640, 480);
            }
        };
        panel.setBorder(BorderFactory.createLineBorder(Color.blue, 5));
        Graph graph = new SingleGraph("Tutorial", false, true);

        try {
            Class.forName("org.h2.Driver");
            conn2 = DriverManager.getConnection("jdbc:h2:file:G:/hs_data/h2_db/test", "sa", "sa");

        } catch (Exception e) {
            e.printStackTrace();
        }
        Statement stmt2 = conn2.createStatement();
        ResultSet rs = stmt2.executeQuery("SELECT count(*) FROM cdr");
        while (rs.next()) {
            totalRows = rs.getInt(1);
        }
        ResultSet rs2 = stmt2.executeQuery("SELECT ANUMBER,BNUMBER FROM CDR LIMIT 1000");
        while (rs2.next()) {
            result = rs2.getString("ANUMBER");
            result2 = rs2.getString("BNUMBER");
            graph.addNode(result);
            graph.addNode(result2);
            for (i = 0; i < 1000; i++)
                graph.addEdge("string" + i, result, result2);
        }

        Viewer viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_GUI_THREAD);
        ViewPanel viewPanel = viewer.addDefaultView(false);
        panel.add(viewPanel);
        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        for (Node node : graph) {
            node.addAttribute("ui.label", node.getId());
        }

        }

}

Before that I was using graph.display() and it was working fine But when I added the graph panel to my custom JPanel it starts behaving like this.


Solution

  • try this:

       viewer.enableAutoLayout();