【问题标题】:How to draw a tree representing a graph of connected nodes?如何绘制表示连接节点图的树?
【发布时间】:2012-04-24 23:35:52
【问题描述】:

我想在 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 );
}

}

我只想画树。我该怎么办?

【问题讨论】:

    标签: java swing swt awt


    【解决方案1】:

    我想你只需要阅读一下 JTree: http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html

    也许还有一些关于 Swing 的其他一般信息

    【讨论】:

    • sry 但我想向树展示一些类似这个链接的东西:lcm.csa.iisc.ernet.in/dsa/img151.gif
    • 不确定是否有免费的库来构建这样的可视化树。尽管使用基本的图形工具,您始终可以自己绘制。
    【解决方案2】:

    我能想到的最简单的方法是编写一个扩展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);
        }
    
    }
    

    尝试画树,如果您无法弄清楚,请发布您在问题中尝试过的内容。

    【讨论】:

      【解决方案3】:

      您可以考虑以下任何一种:

      【讨论】:

        【解决方案4】:

        我想说Abego's TreeLayout 也值得一试。它本质上是一种树布局算法,因此可以与任何绘图机制一起使用,但它还包含一些在 SVG 和 Swing 中绘制图形的演示/示例。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-26
          • 2018-01-20
          • 2018-06-30
          • 2011-08-11
          • 2014-09-11
          • 1970-01-01
          • 2021-08-15
          • 2011-01-14
          相关资源
          最近更新 更多