Java JTree is tree node above another tree node

Description

Java JTree is tree node above another tree node

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

public class Main {
   public static void main(String args[]) {
      final JFrame f = new JFrame("JTree Demo");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new FlowLayout());
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("A");
      DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("B");
      DefaultMutableTreeNode c3 = new DefaultMutableTreeNode("C");
      root.add(c1);/*from  w w  w  .  j  a v a 2 s.  c  o  m*/
      root.add(c2);
      root.add(c3);

      c1.add(new DefaultMutableTreeNode("1"));
      c1.add(new DefaultMutableTreeNode("2"));

      c2.add(new DefaultMutableTreeNode("3"));
      c2.add(new DefaultMutableTreeNode("4"));

      c3.add(new DefaultMutableTreeNode("5"));
      DefaultMutableTreeNode n6 = new DefaultMutableTreeNode("6");

      c3.add(n6);

      JTree t = new JTree(root);

      System.out.println(isAbove(root, c3));

      c.add(new JScrollPane(t));
      f.pack();
      f.setVisible(true);
   }
   /**
    * Returns whether a node is above another node (one of it's parents).
    * <p>
    * Moves up from <code>below</code> to all parents until <code>above</code>
    * is found or a parent node above has no parent.
    * <p>
    * Compares the nodes object <strong>references</strong>
    *
    * @param  above node that shall be above <code>below</code>
    * @param  below node that shall be below <code>above</code>
    * @return       true if <code>above</code> is one of <code>below</code>'s
    *               parents
    */
   public static boolean isAbove(TreeNode above, TreeNode below) {
       if (above == null) {
           throw new NullPointerException("above == null");
       }

       if (below == null) {
           throw new NullPointerException("below == null");
       }
       TreeNode parent = below.getParent();
       while (parent != null) {
           if (parent == above) {
               return true;
           }
           parent = parent.getParent();
       }
       return false;
   }

}



PreviousNext

Related