gpt4 book ai didi

java - JFrame 中的 mxGraph 中心

转载 作者:行者123 更新时间:2023-12-01 13:05:15 24 4
gpt4 key购买 nike

我正在尝试将具有分层布局的 mxGraph 居中,以便在 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();

}
}

最佳答案

这是使图表居中的另一种方法。

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

这对我来说非常有用。

关于java - JFrame 中的 mxGraph 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23313003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com