我需要创建一个有向图和一个显示此图的图像。
我尝试使用DirectedGraph创建图形,它在内部存储正确,我测试了它,但我无法从它创建一个图像来显示在E4 RCP应用程序中。
这是我的代码:
import org.jgraph.JGraph;
import org.jgrapht.DirectedGraph;
import org.jgrapht.ext.JGraphModelAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
DirectedGraph <String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
addVertexes();
addEdges();
//Create image from graph
JGraphModelAdapter<String, DefaultEdge> graphModel = new JGraphModelAdapter<String, DefaultEdge>(graph);
JGraph jgraph = new JGraph (graphModel);
BufferedImage img = jgraph.getImage(Color.WHITE, 5);但是显然img总是空的。为什么会这样?我如何才能将其更改为正常工作?
发布于 2014-08-21 16:44:13
只需阅读JGraphX并尝试使用它,所以对我来说它工作得很好!这是我现在代码的一个例子(减少了顶点和边的例子)。
mxGraph graphMx = new mxGraph();
graphMx.insertVertex(graphMx.getDefaultParent(), "Start", "Start", 0.0, 0.0, 50.0, 30.0, "rounded");
graphMx.insertVertex(graphMx.getDefaultParent(), "Ende", "Ende", 0.0, 0.0, 50.0, 30.0, "rounded");
graphMx.insertEdge(graphMx.getDefaultParent(), null, "", ((mxGraphModel)graphMx.getModel()).getCell("Start"), ((mxGraphModel)graphMx.getModel()).getCell("Ende"));
mxIGraphLayout layout = new mxHierarchicalLayout(graphMx);
layout.execute(graphMx.getDefaultParent());
BufferedImage image = mxCellRenderer.createBufferedImage(graphMx, null, 1, Color.WHITE, true, null);
return image;发布于 2014-09-26 22:44:55
您还可以将其放在JFRAME上,并从该帧生成图像。-Jan
发布于 2020-12-24 15:24:18
我的答案类似于@HexFlex,但我让它以同样的方式工作,尽管我不确定如何自定义绘图:
String GRAPH_FILE_PATH = "somwhere/u/want.png";
public static <V, E> File drawGraph(Graph<V, E> graph) throws IOException {
JGraphXAdapter<V, E> graphAdapter = new JGraphXAdapter<V, E>(graph);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, new Color(0f,0f,0f,.5f), true, null);
File imgFile = new File(GRAPH_FILE_PATH);
ImageIO.write(image, "PNG", imgFile);
return imgFile;
}编辑:顺便说一句,代码来自https://www.baeldung.com/jgrapht,我只是把它重构成一个函数
https://stackoverflow.com/questions/25420449
复制相似问题