How to add two edges having the same label (but different endpoints) in JUNG?

旧时模样 提交于 2019-12-04 13:11:34

Labels are not required to be the toString() of the edges; that's just the default. Take a look at PluggableRendererContext to see how to supply a Transformer that provides a property for each element of the graph.

I'd also check out the section in the JUNG 2 manual (on the wiki) that talks about user data: http://sourceforge.net/apps/trac/jung/wiki/JUNGManual#UserData

When I have this problem, I make my label String (your is already a String) and make its value like this: "ID_OF_FIRST_VERTEX:ID_OF_SECOND_VERTEX:EDGE_VALUE". Then, to display just a value, I do use transformation. Its simple, it just takes the edge_value from name of edge.

In this sample I use a separator ":".

VisualizationViewer vv = new VisualizationViewer(layout, dim);
//other operations
vv.getRenderContext().setEdgeLabelTransformer(new Transformer<String, String>() {
    @Override
    public String transform(String c) {
        return StringUtils.substringAfterLast(c, ":");
    }
});

Of course you dont have to use StringUtils from Apache Commons, a normal String.subString will work here as well.

Hope it helps.

2c00L

Here is an MCVE example.

package stackoverflow;

import javax.swing.JFrame;
import org.apache.commons.collections15.Transformer;
import edu.uci.ics.jung.algorithms.layout.FRLayout;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.visualization.VisualizationViewer;


public class JungNetwork {

public static Graph<String, String> getGraph() 
{
    Graph<String, String> g = new DirectedSparseMultigraph<String, String>();

    g.addVertex("v1");
    g.addVertex("v2");
    g.addVertex("v3");
    g.addEdge("label1", "v1", "v2");
    g.addEdge("label2", "v2", "v3");
    g.addEdge("label3", "v3", "v1");
    return g;
}


public static void main(String[] args) 
{
    JFrame f = new JFrame();
    final Graph<String, String> g = getGraph();
    VisualizationViewer<String, String> vv =    new VisualizationViewer<String, String>(new FRLayout<String, String>(g));

    final Transformer <String, String> edgeLabel = new Transformer<String, String>(){

        @Override
        public String transform(String edge) {
            // TODO Auto-generated method stub
            if (edge.equals("label1")|| edge.equals("label2")){
                return "label1";
            }else
            return "label3";
        }

    };


    vv.getRenderContext().setLabelOffset(15);
    vv.getRenderContext().setEdgeLabelTransformer(edgeLabel);

    f.getContentPane().add(vv);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
}


}

The Result:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!