0

JFrame でセルを動的に配置するために、hierarchicalLayout を持つ mxGraph を中央に配置しようとしています。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();

    }
}
4

2 に答える 2

1

グラフを中央に配置する別の方法を次に示します。

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

これは私にとってとてもうまくいきます。

于 2016-04-29T21:13:18.890 に答える
0

フレームのレイアウト マネージャーを変更して、GrigBagLayout を使用します。

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

次に、デフォルトの制約を使用してコンポーネントをフレームに追加します。

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

なぜこれが機能するのかを理解するには、Swing チュートリアルの How to Use GridBagLayoutに関するセクション、特にweightx/weighty制約がどのように機能するかを説明するセクションを読んでください。

最後に、すべてのコンポーネントがフレームとフレームの子パネルに追加された後、コンストラクターの最後のステートメントとして f.setVisible() メソッドを呼び出す必要があります。

于 2014-04-26T15:45:59.627 に答える