如何在JUNG图形可视化中添加自定义顶点标签?

问题描述:

如何在 JUNG 图表可视化中使用自定义顶点标签?

How to use custom vertex labels in JUNG graph visualization?

我正在关注 Jung 2.0 Tutorial ,我发现 setVertexLabelTransformer()可用于标记顶点,但据我所知,这些标签无法自定义。

I am following Jung 2.0 Tutorial where I found that setVertexLabelTransformer() can be used to label the vertices, but these labels cannot be customized, to my knowledge.

For例如,下面的代码生成三个顶点,顶点标签1,2,4:

For example, the below code produces three vertices, having vertex-labels 1,2,4:

import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import java.awt.Dimension;
import javax.swing.JFrame;

public class SimpleGraphView {
    Graph<Integer, String> g;

    public SimpleGraphView() {       
        g = new SparseMultigraph<Integer, String>();
        g.addVertex((Integer)1);
        g.addVertex((Integer)2);
        g.addVertex((Integer)4); 
    }

    public static void main(String[] args) {
        SimpleGraphView sgv = new SimpleGraphView(); 
        Layout<Integer, String> layout = new CircleLayout(sgv.g);
        layout.setSize(new Dimension(800,800));  
        BasicVisualizationServer<Integer,String> vv =
            new BasicVisualizationServer<Integer,String>(layout);
        vv.setPreferredSize(new Dimension(850,850)); 

        JFrame frame = new JFrame("Simple Graph View");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(vv); 
        frame.pack();
        frame.setVisible(true);       
    }
}

如何添加q0等标签?

由于您已经定义了的泛型SparseMultigraph< V,E> as SparseMultigraph< Integer,String> 其中顶点的泛型 V 为整数,边缘的泛型E为 String ,因此每个顶点的标签值都在 Integer 中,并且每个边的标签都在 String 。因此,如果您希望每个顶点都有q1,v2等名称,请使用 String 表示通用 V ,所以你可以传递一个这样的顶点名称 g.addVertex(q1);

Since you have defined the generics of SparseMultigraph<V, E> as SparseMultigraph<Integer, String> where the generic V for vertex as Integer and the generic E for edge as String, hence each vertex's label value is in Integer and each edge's label in String. So, if you want each vertex by names like q1, v2, etc., use String for generic V, so you can pass a vertex name like this g.addVertex("q1");