简体   繁体   English

在Jung中更改(重命名)顶点标签

[英]Change(rename) vertex label in jung

Is there a way to change vertex label? 有没有办法更改顶点标签?
For example, in my JUNG graph app, I have two vertexes A and B, 例如,在我的JUNG图形应用中,我有两个顶点A和B,
how can I rename just an special vertex label? 如何仅重命名特殊的顶点标签?

Now i use this method but it changes all vertex name. 现在,我使用此方法,但它会更改所有顶点名称。

vv.getRenderContext().setVertexLabelTransformer(new Transformer<String,String>() {
 @Override
 public String transform(String i) {
 return "test";
 }
 });

Thanks for your help. 谢谢你的帮助。

There are a few things to consider here. 这里有几件事情要考虑。

A Transformer<S, T> is just a functional interface [1] for a class that, given an object of type S , returns an object of type T . Transformer<S, T>只是一个类的功能接口 [1],该类在给定类型S的对象的情况下返回类型T的对象。 The behavior of the transform method can be anything you like that returns an object of type T . 您可以使用transform方法的行为来返回T类型的对象。

Because it's a functional interface, you can make the syntax a little bit clearer (assuming you're using Java 8+) with a lambda expression. 因为它是一个功能接口,所以您可以使用lambda表达式使语法更加清晰(假设您使用的是Java 8+)。

So a naive way to rename just "A" to "B" (using Java 8 lambdas) could be the following: 因此,将“ A”重命名为“ B”(使用Java 8 lambda)的一种简单方法是:

vv.getRenderContext().setVertexLabelTransformer(i -> {
      return i.equals("A")
          ? "B"
          : i;  
    }

However, this is a terrible solution because it hardcodes the mapping and doesn't allow you to change the name of other nodes, or to change the names again (say, in response to user input), without further code changes. 但是,这是一个糟糕的解决方案,因为它对映射进行了硬编码,并且不允许您更改其他节点的名称或再次更改名称(例如,响应用户输入),而无需进行进一步的代码更改。

A more robust way to do this would be to have a Map<S, T> called labels that your function could reference: 执行此操作的更可靠的方法是让Map<S, T>称为labels ,您的函数可以引用该labels

vv.getRenderContext().setVertexLabelTransformer(i -> labels.get(i));

This way you can update labels as much as you like. 这样,您可以随意更新labels

You may also want to consider whether your nodes should be represented by String objects, or whether they should be objects that contain a String field that you can use as a label. 您可能还需要考虑节点是否应该由String对象表示,或者它们是否应该是包含可以用作标签的String字段的对象。 I generally find that it's a good idea to decouple the node object from its label (among other things, that allows the labels to be non-unique, which the node objects can't be). 我通常会发现,将节点对象与其标签脱钩是一个好主意(除其他事项外,这允许标签是非唯一的,而节点对象不能这样)。

[1] And in fact version 3.0 of JUNG will just use java.util.Function in place of Transformer . [1]实际上,JUNG的3.0版将只使用java.util.Function代替Transformer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM