3

I'm trying to solve a task where i need to display graph in Swing. Found JGraph framework (which is now called JGraphX). In samples the graph.insertVertex(...) method is used for adding Vertices and the graph.insertEdge(...) method for Edges - ok it works fine.

But how can i remove that Vertex afterwards?

Frodo Baggins
  • 8,290
  • 6
  • 45
  • 55
shagi
  • 629
  • 8
  • 25

1 Answers1

5

It looks like you can use the mxGraph.removeCells method for removing a vertex. I have modified the HelloWorld example that is included in JGraphX (using release 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);
    }
}
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28