加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何绘制代表连接节点图的树?

发布时间:2020-12-14 05:06:51 所属栏目:Java 来源:网络整理
导读:我想在 Java GUI中显示树,但我不知道如何.树代表连接节点的图形,如下所示: 我应该说我有自己的树类: public class BinaryTree {private BinaryNode root;public BinaryTree( ){ root = null;}public BinaryTree( Object rootItem ){ root = new BinaryNode
我想在 Java GUI中显示树,但我不知道如何.树代表连接节点的图形,如下所示:

我应该说我有自己的树类:

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 );
}

}

我只想画树.我应该怎么做?

解决方法

我可以想到的最简单的方法是编写一个扩展JPanel并覆盖其paintComponent()方法的类.在paint方法中,您可以遍历树并绘制每个节点.这里有一个简单的例子:
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);
    }

}

在树上画一个刺,如果你不能弄清楚你在你的问题上尝试了什么.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读