如何在GUI Java中绘制/呈现树?

时间:2019-06-02 11:34:15

标签: java

我正在尝试绘制具有0或2个子代的二叉树。我尝试了以下方法,但是它所做的是使它保持对齐。我试图阅读“ https://llimllib.github.io/pymag-trees/”,但这是python格式的,无法从中了解很多

      public void drawTree(Graphics g, Node root) {        //actually draws the tree
      int dx, dy, dx2, dy2;
      int SCREEN_WIDTH=800;     //screen size for panel
      int SCREEN_HEIGHT=700;
      int XSCALE, YSCALE;  
      XSCALE=SCREEN_WIDTH/t.totalnodes;     //scale x by total nodes in tree
      YSCALE=(SCREEN_HEIGHT-ys)/(t.maxheight+1);      //scale y by tree height

      if (root != null) {    // inorder traversal to draw each node
        drawTree(g, root.left);     // do left side of inorder traversal 
        dx = root.x * XSCALE; // get x,y coords., and scale them 
        dy = root.y * YSCALE +ys;
        String s = String.valueOf(root.freq) ; //get the word at this node;
        g.drawString(s, dx, dy);           // draws the word
// this draws the lines from a node to its children, if any
        if(root.left!=null){      //draws the line to left child if it exists
          dx2 = root.left.x * XSCALE; 
          dy2 = root.left.y * YSCALE +ys;
          g.drawLine(dx,dy,dx2,dy2);
        }
        if(root.right!=null){       //draws the line to right child if it exists
          dx2 = root.right.x * XSCALE;     //get right child x,y scaled position
          dy2 = root.right.y * YSCALE + ys;
          g.drawLine(dx,dy,dx2,dy2);
        }
        drawTree(g, root.right);    //now doing right side of inorder traversal 
      }
    }
}

0 个答案:

没有答案