我正在尝试解决一个需要在Swing中显示图形的任务。找到JGraph框架(现在称为JGraphX)。在示例中,graph.insertVertex(...)方法用于添加顶点,而graph.insertEdge(...)方法用于Edge-好的,它可以正常工作。

但是之后我该如何删除该顶点?

最佳答案

看起来您可以使用mxGraph.removeCells方法删除顶点。我已经修改了HelloWorld中包含的JGraphX示例(使用发行版3.4.1):

import com.mxgraph.swing.*;
import com.mxgraph.view.*;
import javax.swing.*;

/**
 * Adapted from https://github.com/jgraph/jgraphx/blob/master/examples
 *              /com/mxgraph/examples/swing/HelloWorld.java
 */
public class GoodbyeVertex extends JFrame {
    private static final long serialVersionUID = -2707712944901661771L;

    public static void main(String[] args) {
        GoodbyeVertex frame = new GoodbyeVertex();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(400, 320);
        frame.setVisible(true);
    }

    public GoodbyeVertex() {
        super("Hello, World!");

        mxGraph graph = new mxGraph();
        Object parent = graph.getDefaultParent();

        graph.getModel().beginUpdate();
        try {
            Object v1 = graph.insertVertex(parent, null, "Hello", 20, 20, 80, 30);
            Object v2 = graph.insertVertex(parent, null, "World!", 240, 150, 80, 30);

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

            // Remove a vertex. The related edge is removed as well.
            graph.removeCells(new Object[]{v1});
        } finally {
            graph.getModel().endUpdate();
        }

        mxGraphComponent graphComponent = new mxGraphComponent(graph);
        getContentPane().add(graphComponent);
    }
}

09-27 17:04