看起来您在问题中遗漏了一些重要的细节,如果没有Minimal, Complete, and Verifiable example,很难说问题出在哪里。
但是,请注意,您尝试采用的样本非常旧。 JGraph 已移至 JGraphX。考虑以下示例,该示例演示了使用JGraphXAdapter 的JGraphT 和JGraphX 的链接。
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jgrapht.ListenableGraph;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.ListenableDirectedWeightedGraph;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.swing.mxGraphComponent;
public class DemoWeightedGraph {
private static void createAndShowGui() {
JFrame frame = new JFrame("DemoGraph");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ListenableGraph<String, MyEdge> g = buildGraph();
JGraphXAdapter<String, MyEdge> graphAdapter =
new JGraphXAdapter<String, MyEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
frame.add(new mxGraphComponent(graphAdapter));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public static class MyEdge extends DefaultWeightedEdge {
@Override
public String toString() {
return String.valueOf(getWeight());
}
}
public static ListenableGraph<String, MyEdge> buildGraph() {
ListenableDirectedWeightedGraph<String, MyEdge> g =
new ListenableDirectedWeightedGraph<String, MyEdge>(MyEdge.class);
String x1 = "x1";
String x2 = "x2";
String x3 = "x3";
g.addVertex(x1);
g.addVertex(x2);
g.addVertex(x3);
MyEdge e = g.addEdge(x1, x2);
g.setEdgeWeight(e, 1);
e = g.addEdge(x2, x3);
g.setEdgeWeight(e, 2);
e = g.addEdge(x3, x1);
g.setEdgeWeight(e, 3);
return g;
}
}
请注意,MyEdge 扩展了 DefaultWeightedEdge 以提供自定义 toString() 以显示边缘权重。一个更干净的解决方案可能是覆盖mxGraph.convertValueToString,检查单元格的内容并根据需要提供自定义标签。 toString 是演示的快捷方式,我还注意到 DefaultWeightedEdge.getWeight() 受到保护,因此无论如何都需要扩展 :)