Java – how to draw a tree representing the connection node graph?

I want to display the tree in the Java GUI, but I don't know how The tree represents the graph of connected nodes, as shown below:

I should say I have my own tree class:

public class BinaryTree  
{
private BinaryNode root;
public BinaryTree( )
{
    root = null;
}

public BinaryTree( Object rootItem )
{
    root = new BinaryNode( rootItem,null,null );
}

public BinaryTree( Object rootItem,BinaryNode a,BinaryNode b )
{
    root = new BinaryNode( rootItem,a,b );
}

public int leavesCount(){
    return BinaryNode.leavesCount(root);
}

public boolean equal(BinaryTree a,BinaryTree b){
    return BinaryNode.equal(a.root,b.root);

}

public void printPreOrder( )
{
    if( root != null )
        root.printPreOrder( );
}

public void printInOrder( )
{
    if( root != null )
       root.printInOrder( );
}

public void printPostOrder( )
{
    if( root != null )
       root.printPostOrder( );
}

public void makeEmpty( )
{
    root = null;
}


public boolean isEmpty( )
{
    return root == null;
}


public void merge( Object rootItem,BinaryTree t1,BinaryTree t2 ) throws MergeAbrot
{
    if( t1.root == t2.root && t1.root != null )
    {
         throw new MergeAbrot("MergeAbrot");

    }

     root=new BinaryNode( rootItem,t1.root,t2.root );

    if( this != t1 )
        t1.root = null;
    if( this != t2 )
       t2.root = null;
}

public int size( )
{
    return BinaryNode.size( root );
}

public int height( )
{
    return BinaryNode.height( root );
}

}

I just want to draw trees What should I do?

Solution

The easiest way I can think of is to write a class that extends JPanel and overrides its paintcomponent () method In the paint method, you can traverse the tree and draw each node Here is a simple example:

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JPanelTest extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        // Draw Tree Here
        g.drawOval(5,5,25,25);
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.add(new JPaneltest());
        jFrame.setSize(500,500);
        jFrame.setVisible(true);
    }

}

Draw a thorn on the tree if you can't figure out what you tried on your problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>