Java – Show weights in JgraphT


I have implemented this Graph:

ListenableDirectedWeightedGraph<String, MyWeightedEdge> g = 
    new ListenableDirectedWeightedGraph<String, MyWeightedEdge>(MyWeightedEdge.class); 

In order to show what the class name says; a simple listenable directed weighted graph. I want to change the label of the edges and instead of the format

return "(" + source + " : " + target + ")"; 

I want it to show the weight of the edge. I realise that all actions on the nodes, e.g. the getEdgesWeight() method, are delegated from the graph and not the edge. How can I show the weight of the edge? Do I have to pass in the Graph to the edge somehow?

Any help is appreciated.

Best Solution

I assume that the class MyWeightedEdge already contains a method such as

public void setWeight(double weight)

If this is indeed the case, then what you need to do is:

Derive your own subclass from ListenableDirectedWeightedGraph (e.g., ListenableDirectedWeightedGraph). I would add both constructor versions, delegating to "super" to ensure compatibility with the original class.

Create the graph as in your question, but using the new class

ListenableDirectedWeightedGraph g = 
    new CustomListenableDirectedWeightedGraph(

Override the method setEdgeWeight as follows:

public void setEdgeWeight(E e, double weight) {
    super.setEdgeWeight(e, weight);

And, last but not least, override the toString method of the class MyWeightedEdge to return the label you want the edge to have (presumably including the weight, which is now available to it).

I hope this helps.

Related Question