2

I am trying to manually draw a tiered tree from a list of nodes. Each node is an object that has information contained in methods, for example:

node.getParent()
node.getChildrenCount()

The problem I got stuck with is drawing a pyramid structure of the tree (correctly indenting the children nodes), with the root being on top in the middle, and children spreading downwards symmetrically.

private void drawTree(Graphics2D graphics) {
        int width = 110;
        int height = 40;
        int y = 10;
        for (int i = 0, nodesSize = nodes.size(); i < nodesSize; i++) {
            AttributedNode node = nodes.get(i);
            Rectangle rectangle;
            if (i == 1) { // draw root
                rectangle = new Rectangle(getRootX(), y, width, height);
            } else {
                if (node.getChildCount() == 1) { // if one child draw beneath
                    rectangle = new Rectangle(getRootX(), y, width, height);
                } else {
                    rectangle = new Rectangle(getRootX() + 40, y, width, height);
                }
            }
            y += 50;
            graphics.draw(rectangle);
            addStringToRectangle(graphics, rectangle, node.getText());
        }
    }

What I have so far: http://img10.imageshack.us/img10/8822/rcsi.png
And what I want to achieve: http://img703.imageshack.us/img703/8416/1o05.png
Any help would be appreciated.

maryokhin
  • 1,058
  • 13
  • 20
  • 1
    This kind of layout tends to be hard to do well. Perhaps it would be easier to only generate a textual representation of the graph in your app and to use e.g. [graphviz / dot](http://www.graphviz.org/) to compile it and to generate the final image? – Michał Kosmulski Sep 20 '13 at 22:16
  • @MichałKosmulski I have tried it before, but the .dot info generated from my ANTLR tree was very bad. But, thanks to your comment I tried again, and managed to implement my own class by extending org.antlr.runtime.tree.DOTTreeGenerator. Haven't found a way yet to runtime transform .dot console output into a graph, but it is definitely an idea. Thanks! – maryokhin Sep 20 '13 at 23:25
  • 1
    Please have a look at this [thread](http://stackoverflow.com/q/4965335/1057230), though it only presented a way to do that on console (not totally as you would like), though with slight modification, I guess you can incorporate that in the Swing Application as well :-) – nIcE cOw Sep 21 '13 at 05:58

1 Answers1

0

Recursion may be provide a nice solution to your problem.

public void drawTree(Node node, Graphics2D graphics) {
    if(node != null){
        //drawTree(node.leftChild);
        //drawTree(node.rightChild);
        //draw this node.
    }
} 

I've used some pseudo code but if you develop this idea it may help. I'd suggest thinking about drawing it on paper dry running this simple idea. Read up on pre order, in order and post order :)

JensG
  • 13,148
  • 4
  • 45
  • 55
Aaron
  • 193
  • 7