Show weights in JgraphT
Asked Answered
V

1

6

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.

Visconti answered 25/9, 2008 at 16:55 Comment(0)
D
2

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(
        MyWeightedEdge.class);

Override the method setEdgeWeight as follows:

public void setEdgeWeight(E e, double weight) {
    super.setEdgeWeight(e, weight);
    ((MyWeightedEdge)e).setWeight(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.

Danette answered 3/12, 2008 at 16:59 Comment(1)
user5915 didn't mention what he used to visualize his graph but I assume it was jgraph. It's like you're telling him to write his own library O.oGonococcus

© 2022 - 2024 — McMap. All rights reserved.