JGrapT 设置无向图

JGrapT setting undirected graph

你好,我一直在网上寻找关于如何在 JGraphT 中制作无向图的答案,但它不起作用,我有这样的东西:

g = new ListenableUndirectedGraph<String, MyEdge>(MyEdge.class);
graphAdapter = new JGraphXAdapter<String, MyEdge>(g);

g.addVertex("a");
g.addVertex("b");
g.addEdge("a","b");

layout = new mxOrganicLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());

component = new mxGraphComponent(graphAdapter);

component.setPreferredSize(new Dimension(dim.width - 50, dim.height - 200));

add(component);

虽然它被定义为无向的,但它显示为有向的

我对您的代码进行了一些改动,应该可以。

去掉箭头的部分在后面

// This part to remove arrow from edge
mxUtils.setCellStyles(graphComponent.getGraph().getModel(),
cells.toArray(), mxConstants.STYLE_ENDARROW, mxConstants.NONE);

所以完整的代码是这样的,这只是一个例子,剩下的就留给你们想象吧:

import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.model.mxGraphModel;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxUtils;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;

import javax.swing.*;
import java.awt.*;
import java.util.Collection;

public class UndirectedGraphClass extends JFrame {

    public static void main(String[] args) {
        new UndirectedGraphClass();
    }

    private UndirectedGraphClass() {

        JGraphXAdapter<String, DefaultEdge> jgxAdapter;
        UndirectedGraph<String, DefaultEdge> g =
                new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);

        g.addVertex("a");
        g.addVertex("b");
        g.addEdge("a", "b");

        jgxAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
        mxGraphComponent graphComponent = new mxGraphComponent(jgxAdapter);
        mxGraphModel graphModel = (mxGraphModel) graphComponent.getGraph().getModel();
        Collection<Object> cells = graphModel.getCells().values();
        // This part to remove arrow from edge
        mxUtils.setCellStyles(graphComponent.getGraph().getModel(),
                cells.toArray(), mxConstants.STYLE_ENDARROW, mxConstants.NONE);
        getContentPane().add(graphComponent);

        mxCircleLayout layout = new mxCircleLayout(jgxAdapter);
        layout.execute(jgxAdapter.getDefaultParent());

        this.setTitle(" some undirected graph ");
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(400, 400));
        this.pack();
        this.setVisible(true);
    }
}

解决方案的灵感来自于此answer