javaswingjgraphx

Center mxGraph in JFrame


I am trying to center an mxGraph that has a hierarchicalLayout to arrange cells dynamically in a JFrame. Every time I render the jFrame, the mxGraph is drawn in the upper-left corner of the frame, and I can't find a way to modify the positioning of the graph. How does one accomplish this?

public class Test {

    public Test() {
        Object v1;
        Object v2;
        Object v3;
        JFrame f = new JFrame();
        f.setSize(500, 500);
        f.setLocation(300, 200);

        mxGraph graph = new mxGraph();
        mxGraphComponent graphComponent = new mxGraphComponent(graph);
        f.getContentPane().add(BorderLayout.CENTER, graphComponent);
        f.setVisible(true);

        Object parent = graph.getDefaultParent();
        graph.getModel().beginUpdate();
        try {
             v1 = graph.insertVertex(parent, null, "node1", 100, 100, 80, 30);
            v2 = graph.insertVertex(parent, null, "node2", 100, 100, 80, 30);
             v3 = graph.insertVertex(parent, null, "node3", 100, 100, 80, 30);

            graph.insertEdge(parent, null, "Edge", v1, v2);
            graph.insertEdge(parent, null, "Edge", v2, v3);

        } finally {
            graph.getModel().endUpdate();
        }

        // define layout
        mxIGraphLayout layout = new mxHierarchicalLayout(graph);

        // layout using morphing
        graph.getModel().beginUpdate();
        try {
            layout.execute(graph.getDefaultParent());
        } finally {
                    graph.getModel().endUpdate();
                    // fitViewport();
        }

    }

    public static void main(String[] args) {
        Test t = new Test();

    }
}

Solution

  • Change the layout manager of the frame to use a GrigBagLayout:

    JFrame f = new JFrame();
    f.setLayout( new GridBagLayout() );
    

    then add your component to the frame using the default constraints:

    //f.getContentPane().add(BorderLayout.CENTER, graphComponent);
    f.add(graphComponent, new GridBagConstraints());
    

    To understand why this works read the section from the Swing tutorial on How to Use GridBagLayout, especially the section that explains how the weightx/weighty constraints work.

    Finally, the f.setVisible() method should be invoked as the last statement in your constructor, AFTER all components have been added to the frame and the frames child panels.