【问题标题】:How to graphically print a generic tree?如何以图形方式打印通用树?
【发布时间】:2014-07-07 08:44:17
【问题描述】:

我必须能够用 Graphviz 表示通用树。 树的每个节点都是这样制作的Node对象:

private static int counter = 0;
private String text = "node";
private Step[] step;
private List<Node> children;
private Node parent = null;

Step 是一个对象,如下所示:

private char char;
private char cipherChar;

表示树的类(树类)包含这些字段和方法:

private Node root;
private Node last;
private Node parent;
private String name;
private String message;

public void print(String indent) {
    ArrayList<Node> tree = new ArrayList<Node>();
    tree = getPreOrderTraversal();
    for(int i = 0; i < tree.size(); i++) {
        tree.get(i).printSoluzione();
    }
}

private String printGraphviz() throws IOException {
    String g = new String("");
    g = g.concat("digraph G {\n");
    if(root == null) 
        g = g.concat("    " + "Empty tree.");
    else {
        ArrayList<Node> nodi = new ArrayList<Node>();
        nodi = getPreOrderTraversal();
        for(int i = 0; i < nodi.size(); i++) {
            if(nodi.get(i).getParent() != null) {
                g = g.concat("\t\"" + nodi.get(i).getParent().getText() + "\" -> \"" + nodi.get(i).getText() + "\"\n");
            }
        }
    }
    g = g.concat("}");
    return g;
}

public void toString(String fileDot){
    try {
        FileOutputStream file = new FileOutputStream(fileDot); 
        PrintStream Output = new PrintStream(file);
        Output.print(this.printGraphviz()); 
        Output.close(); 
        File f = new File(fileDot); 
        String arg1 = f.getAbsolutePath(); 
        String arg2 = arg1 + ".png"; 
        String[] c = {"dot", "-Tpng", arg1, "-o", arg2};
        Process p = Runtime.getRuntime().exec(c); 
        int err = p.waitFor(); 
    }
    catch(IOException e1) {
        System.out.println(e1);
    }
    catch(InterruptedException e2) {
        System.out.println(e2);
    }
}

使用这段代码,当我调用函数print("") 时,它会生成如下图片: http://www.mediafire.com/convkey/5a9c/km8jkb6wm9qn4fyfg.jpg?size_id=4

但我希望它存在于数组 Step 的每个节点中,然后是这样的图像: http://www.mediafire.com/convkey/4c2e/8267kphkp0824o3fg.jpg?size_id=5

换句话说,我希望显示每个节点的所有步骤,而不是节点的名称。 如何更改方法printGraphviz()

谢谢!

【问题讨论】:

    标签: tree graphviz


    【解决方案1】:

    您还没有显示将节点名称写入字符串g 的代码,因此我无法准确说明如何编写修改后的代码。但是,您需要使用节点的 label 属性,以便最终得到字符串 g,包括如下所示的行:

    node0 [label="A=b"]
    node1 [label="A=b\nD=f"]
    

    ...等。有关详细信息,请参阅 GraphViz 文档中 Node, Edge and Graph Attributes 中的 label 条目。

    【讨论】:

      猜你喜欢
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      相关资源
      最近更新 更多