0

我需要创建一个有向图和显示此图的图像。

我尝试使用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 始终为空。为什么会这样,我怎样才能改变它以正常工作?

4

3 回答 3

1

刚刚阅读了 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-08-21T08:44:12.550 回答
0

您也可以将其放在 JFRAME 上并从该帧生成图像。-一月

于 2014-09-26T14:44:54.683 回答
0

我的答案类似于@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,我只是将它重构为一个函数

于 2020-12-24T07:24:18.070 回答