Add GraphStream graph into my custom jPanel

前端 未结 1 1073
予麋鹿
予麋鹿 2021-01-25 11:25

I am working on GraphStream library. For now, When I run my program it opens new window for my graph and separate window for my graph. I tried to create a JFrame an

相关标签:
1条回答
  • 2021-01-25 11:55

    As shown in Graph Visualization: Advanced view: Integrating the viewer in your GUI, "you will need to create the viewer by yourself." Also, call setVisible() after you have constructed the frame.

    It shows error on frame.add(view).

    It looks like the tutorial cited is a little dated. The Viewer method addDefaultView() now returns a ViewPanel, which can be added to a Container. In the complete example below, a border is set on an enclosing JPanel having GridLayout, and that panel is added to the frame. Also note the need to give the panel a preferred size by overriding getPreferredSize(). Resize the window to see the effect.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import org.graphstream.graph.*;
    import org.graphstream.graph.implementations.*;
    import org.graphstream.ui.swingViewer.*;
    import org.graphstream.ui.view.*;
    
    /** @see https://stackoverflow.com/a/45055683/230513 */
    public class GraphSwing {
    
        public static void main(String args[]) {
            EventQueue.invokeLater(new GraphSwing()::display);
        }
    
        private void display() {
            JFrame frame = new JFrame();
            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);
            graph.addEdge("AB", "A", "B");
            Node a = graph.getNode("A");
            a.setAttribute("xy", 1, 1);
            Node b = graph.getNode("B");
            b.setAttribute("xy", -1, -1);
            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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题