簡體   English   中英

如何繪制表示連接節點圖的樹?

[英]How to draw a tree representing a graph of connected nodes?

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

}

嘗試繪制樹,如果您無法弄清楚,請發布您在問題中嘗試過的內容。

我會說也值得查看Abego 的 TreeLayout 它本質上是一種樹布局算法,因此可以與任何繪圖機制一起使用,但它還包含一些在 SVG 和 Swing 中繪制圖形的演示/示例。

我想你只需要閱讀 JTree: http : //docs.oracle.com/javase/tutorial/uiswing/components/tree.html

也許還有其他一些關於 Swing 的一般信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM