I'm trying to draw a binary tree using swing and awt in java. I can already show the nodes of the tree but I can not draw the rows of a parent node to their children. I have the Node, TreeGUI, DrawTree, and Main classes. This image is like the exit without the lines.
Myintentionistoshowrowsfromaparentnodetotheirchildnodes.ItriedtousethedrawLine
methodofclassGraphics
butitlookedlikethis:
ThedrawTreemethoddefinesthepositionofthevaluesofnodesonthescreenandsavesthepositionofnodesinArrayLists.ThedrawLinemethoddrawsthelines.Ibelievetherowsarethiswaybecausethevaluesaresavedinthatparticularorder.I'vetriedinseveralwaysandcannotconnectthelinescorrectly.HowcanIshowonlyaparent'srowstotheirchildren?
publicclassTreeGUIextendsJFrame{privateJPanelcontentPane;publicNodenode;publicDrawTreedrawer;/***Createtheframe.*/publicTreeGUI(Nodenode){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100,100,500,500);contentPane=newJPanel();contentPane.setBorder(newEmptyBorder(5,5,5,5));contentPane.setLayout(newBorderLayout(0,0));drawer=newDrawTree(node);contentPane.add(drawer);setContentPane(contentPane);this.node=node;setVisible(true);}}classDrawTreeextendsJPanel{publicNodenode;publicstaticArrayListlistX=newArrayList();publicstaticArrayListlistY=newArrayList();publicDrawTree(Nodenode){this.node=node;}@OverrideprotectedvoidpaintComponent(Graphicsg){//TODOAuto-generatedmethodstubg.setFont(newFont("Tahoma", Font.BOLD, 20));
DrawTree(g, 0, getWidth(), 0, getHeight() / node.getheight(node), node);
listX.clear();
listY.clear();
}
public void DrawTree(Graphics g, int StartWidth, int EndWidth, int StartHeight, int Level, Node node) {
String data = String.valueOf(node.getValue());
g.setFont(new Font("Tahoma", Font.BOLD, 20));
FontMetrics fm = g.getFontMetrics();
int dataWidth = fm.stringWidth(data);
g.drawString(data, (StartWidth + EndWidth) / 2 - dataWidth / 2, StartHeight + Level / 2);
listX.add((StartWidth + EndWidth) / 2 - dataWidth / 2);
listY.add(StartHeight + Level / 2);
drawLine(g, node);
if (node.getLeft() != null) {
DrawTree(g, StartWidth, (StartWidth + EndWidth) / 2, StartHeight + Level, Level, node.getLeft());
}
if (node.getRight() != null)
DrawTree(g, (StartWidth + EndWidth) / 2, EndWidth, StartHeight + Level, Level, node.getRight());
}
public void drawLine(Graphics g, Node node){
for (int i=1; i < listY.size(); i++)
g.drawLine((int)listX.get(i-1), (int)listY.get(i-1), (int)listX.get(i), (int)listY.get(i));
}
}
method main
public static void main(String[] args) {
Node raiz = null;
raiz = raiz.insert(raiz, 35);
raiz.insert(raiz, 25);
raiz.insert(raiz, 75);
raiz.insert(raiz, 30);
raiz.insert(raiz, 20);
raiz.insert(raiz, 12);
raiz.insert(raiz, 6);
raiz.insert(raiz, 23);
raiz.insert(raiz, 90);
TreeGUI gui = new TreeGUI(raiz);
}