java 在JFrame中将mxGraph居中

5n0oy7gb  于 2022-12-02  发布在  Java
关注(0)|答案(3)|浏览(141)

我尝试将一个mxGraph居中,这个mxGraph有hierarchicalLayout,以便在JFrame中动态排列单元格。每次渲染jFrame时,mxGraph都被绘制在框架的左上角,我找不到修改图形位置的方法。如何实现这一点?

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

    }
}
cngwdvgl

cngwdvgl1#

下面是另一种使图形居中的方法。

//Before you add a vertex/edge to graph, get the size of layout
    widthLayout = graphComponent.getLayoutAreaSize().getWidth();
    heightLayout = graphComponent.getLayoutAreaSize().getHeight();

    //if you are done with adding vertices/edges,
    //we need to determine the size of the graph

    double width = mxGraph.getGraphBounds().getWidth();
    double height = mxGraph.getGraphBounds().getHeight();

    //set new geometry
    mxGraph.getModel().setGeometry(mxGraph.getDefaultParent(), 
            new mxGeometry((widthLayout - width)/2, (heightLayout - height)/2,
                    widthLayout, heightLayout));

这对我很有用。

vojdkbi0

vojdkbi02#

更改框架的布局管理器以使用GrigBagLayout:

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

然后使用默认约束将组件添加到框架:

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

要理解为什么这样做,请阅读Swing教程中关于如何使用GridBagLayout的部分,特别是解释weightx/weighty约束如何工作的部分。
最后,f.setVisible()方法应该作为构造函数中的最后一条语句调用,在所有组件都添加到框架和框架子面板之后。

tpxzln5u

tpxzln5u3#

mxGraphComponent component = new mxGraphComponent(graphAdapter);

...

component.getGraph().getModel().setGeometry(component.getGraph().getDefaultParent(),
        new mxGeometry(10, 10, 0, 0));

相关问题