
 import javax.swing.* ;
 import java.awt.* ;
 import java.awt.event.* ;
 import java.awt.geom.* ;

 class ABBPanel extends JPanel { 

  private class Node {

   int info ;
   Node esq, dir ;

   /**
    @param inf Valor do nó
   */
   public Node (int inf) { 
    info = inf ;
   }

  }

  private Node raiz ;  

  public ABBPanel () { 
   super() ;
  }

  public void paintComponent ( Graphics g ) { 
   Graphics2D g2d = ( Graphics2D ) g ;
   paintNodes(g2d, raiz, getWidth() / 2, 100, 300) ;
  }
   
  /**
   @param pt Ponteiro para nó
   @param x Posição horizontal do nó
   @param y Posição vertival do nó
   @param dist Distância entre os filhos
  */
  private void paintNodes(Graphics2D g, Node pt, int x, int y, int dist) { 
   if ( pt != null ) { 
    g.setColor(Color.BLUE) ;
    int xEsq = x - ( dist / 2 ) ; 
    int xDir = x + ( dist / 2 ) ;
    int yEsqDir = y + 60 ;
    if ( pt.esq != null ) { 
     g.drawLine(x, y, xEsq, yEsqDir) ;
    }
    if ( pt.dir != null ) {
     g.drawLine(x, y, xDir, yEsqDir) ;
    }    
    g.setColor(Color.RED) ;
    g.fill(new Arc2D.Float(x - 20, y - 20, 40, 40, 0, 360, Arc2D.PIE));
    g.setColor(Color.YELLOW) ;
    g.drawString(Integer.toString(pt.info), x, y) ;
    paintNodes(g, pt.esq, xEsq, yEsqDir, dist/2);
    paintNodes(g, pt.dir, xDir, yEsqDir, dist/2);
   }
  }

  private void add(Node pt, int inf) { 
   if ( pt.info >= inf )
    if ( pt.esq == null ) {
     pt.esq = new Node(inf) ;
    } else 
     add(pt.esq, inf) ;
   else 
    if ( pt.dir == null ) 
     pt.dir = new Node(inf) ;
    else
     add(pt.dir, inf) ;
  }

  /**
   @param inf Valor do nó
  */
  public void add(int inf) {
   if ( raiz == null ) { 
    raiz = new Node(inf) ; 
   } else
    add(raiz, inf) ;
  } 

 }

 class ABBWindow extends JFrame implements ActionListener { 

  private JTextField tf ;
  private JButton btn ;
  private ABBPanel AP;

  public ABBWindow ( ) { 
   super("Árvore Binária de Busca") ;
   setSize(500, 500) ;
   setVisible(true); 
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
   //
   tf = new JTextField() ;
   btn = new JButton("Adicionar nó") ;
   btn.addActionListener(this) ;
   tf.setColumns(10) ;
   //
   AP = new ABBPanel() ;
   AP.add(tf) ;
   AP.add(btn) ;
   //
   add(AP) ;
  }

  public void actionPerformed(ActionEvent e) {
   if ( (e.getSource()) instanceof JButton ) {
    AP.add(Integer.parseInt(tf.getText()));
    AP.repaint() ;
   }
  }

  public static void main ( String[] args ) {
	ABBWindow AW = new ABBWindow() ;
  }

 }