您好,我一直在互联网上寻找如何在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。