I am trying to model a weighted and directed graph in java. I am using jgraph and jgraphT libraries to do it. By reading the tutorials I managed to model a directed graph but I am confused how I can add weight to the edges. In fact, using "setEdgeWeight", I can do it but I also need to visualize this on the graph. Anyone knows how to it?
Following is my code:
ListenableDirectedWeightedGraph<String, DefaultWeightedEdge> g =
new ListenableDirectedWeightedGraph<>(
DefaultWeightedEdge.class);
// create a visualization using JGraph, via the adapter
jgAdapter = new JGraphModelAdapter<>(g);
jgraph = new JGraph(jgAdapter);
adjustDisplaySettings(jgraph);
getContentPane().add(jgraph);
resize(DEFAULT_SIZE);
// add some hard-coded sample data (graph manipulated via JGraphT)
//First the vertices
g.addVertex("input page");
g.addVertex("vertex1");
g.addVertex("vertex2");
g.addEdge("vertex2", "input page");
g.addEdge("vertex1", "input page");
g.setEdgeWeight(g.getEdge("vertex2", "input page"), 1000);
Although the code assigns weight, while I try to visualize it, I see no weight label on the edges.
positionVertexAt("input page", 130, 40);
positionVertexAt("vertex2", 150, 10);
positionVertexAt("vertex1", 110, 70);
adjustDisplaySettings(jgraph);
getContentPane().add(jgraph);
resize(DEFAULT_SIZE);
JFrame frame = new JFrame();
frame.getContentPane().add(jgraph);
frame.setTitle("JGraphT Adapter to JGraph Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
Using the following class, I can generate a static value of weight. But I need to generate the weights dynamically while expanding the graph.
public class MyWeightedEdge extends DefaultWeightedEdge {
public MyWeightedEdge() {
super();
}
@Override
public String toString() {
return Double.toString(2.0);
}
}