Queue for Binary Tree Node

I need to create a simple Queue class for Binary Tree Node. The class consist of only enqueue and dequeue, I cannot use the Collection Interface though. But I have no idea how to do it. Below is my Binary Tree Node Class.
public class BTNode {
     private customer     item;
     private BTNode     left;
     private BTNode     right;
     public BTNode() {// constructor
          item = null;
          left = right = null;
     public BTNode(customer newItem) {// constructor
          item = newItem.clone();
          left = right = null;
     public void setItem(customer newItem) {// set methods
          item = newItem.clone();
     public void setLeft(BTNode newLeft) {
          left = newLeft;
     public void setRight(BTNode newRight) {
          right = newRight;
     public customer getItem() {     // get methods
          return item;
     public BTNode getLeft() {
          return left;
     public BTNode getRight() {
          return right;
public class Queue1 extends BTNode {
    public Queue1() {
        super();
    public void enqueue(BTNode newItem) {
    public void dequeue() {
}

public class Queue1 extends BTNode {Why do you think that the queue should extend BTNode?
You probably want to aggregate a List.
Kaj

Similar Messages

  • CTE for Count the Binary Tree nodes

    i have the table structure like this :
    Create table #table(advId int identity(1,1),name nvarchar(100),Mode nvarchar(5),ReferId int )
    insert into #table(name,Mode,ReferId)values('King','L',0)
    insert into #table(name,Mode,ReferId)values('Fisher','L',1)
    insert into #table(name,Mode,ReferId)values('Manasa','R',1)
    insert into #table(name,Mode,ReferId)values('Deekshit','L',2)
    insert into #table(name,Mode,ReferId)values('Sujai','R',2)
    insert into #table(name,Mode,ReferId)values('Fedric','L',3)
    insert into #table(name,Mode,ReferId)values('Bruce','R',3)
    insert into #table(name,Mode,ReferId)values('paul','L',4)
    insert into #table(name,Mode,ReferId)values('walker','R',4)
    insert into #table(name,Mode,ReferId)values('Diesel','L',5)
    insert into #table(name,Mode,ReferId)values('Jas','R',5)
    insert into #table(name,Mode,ReferId)values('Edward','L',6)
    insert into #table(name,Mode,ReferId)values('Lara','R',6)
    select *from #table
    How do i write the CTE for count the Binary tree nodes on level basis. Here is the example,
    now,what i want to do is if i'm going to calculate the Count of the downline nodes.which means i want to calculate for '1' so the resultset which i'm expecting
    count level mode
    1 1 L
    1 1 R
    2 2 L
    2 2 R
    4 3 L
    2 3 R
    How do i acheive this,i have tried this
    with cte (advId,ReferId,mode,Level)
    as
    select advId,ReferId,mode,0 as Level from #table where advid=1
    union all
    select a.advId,a.ReferId,a.mode ,Level+1 from #table as a inner join cte as b on b.advId=a.referId
    select *From cte order by Level
    i hope its clear. Thank you

    See Itzik Ben-Gan examples for the subject
    REATE TABLE Employees
      empid   int         NOT NULL,
      mgrid   int         NULL,
      empname varchar(25) NOT NULL,
      salary  money       NOT NULL,
      CONSTRAINT PK_Employees PRIMARY KEY(empid),
      CONSTRAINT FK_Employees_mgrid_empid
        FOREIGN KEY(mgrid)
        REFERENCES Employees(empid)
    CREATE INDEX idx_nci_mgrid ON Employees(mgrid)
    SET NOCOUNT ON
    INSERT INTO Employees VALUES(1 , NULL, 'Nancy'   , $10000.00)
    INSERT INTO Employees VALUES(2 , 1   , 'Andrew'  , $5000.00)
    INSERT INTO Employees VALUES(3 , 1   , 'Janet'   , $5000.00)
    INSERT INTO Employees VALUES(4 , 1   , 'Margaret', $5000.00) 
    INSERT INTO Employees VALUES(5 , 2   , 'Steven'  , $2500.00)
    INSERT INTO Employees VALUES(6 , 2   , 'Michael' , $2500.00)
    INSERT INTO Employees VALUES(7 , 3   , 'Robert'  , $2500.00)
    INSERT INTO Employees VALUES(8 , 3   , 'Laura'   , $2500.00)
    INSERT INTO Employees VALUES(9 , 3   , 'Ann'     , $2500.00)
    INSERT INTO Employees VALUES(10, 4   , 'Ina'     , $2500.00)
    INSERT INTO Employees VALUES(11, 7   , 'David'   , $2000.00)
    INSERT INTO Employees VALUES(12, 7   , 'Ron'     , $2000.00)
    INSERT INTO Employees VALUES(13, 7   , 'Dan'     , $2000.00)
    INSERT INTO Employees VALUES(14, 11  , 'James'   , $1500.00)
    The first request is probably the most common one:
     returning an employee (for example, Robert whose empid=7) 
    and his/her subordinates in all levels. 
    The following CTE provides a solution to this request:
    WITH EmpCTE(empid, empname, mgrid, lvl)
    AS
      -- Anchor Member (AM)
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = 7
      UNION ALL
      -- Recursive Member (RM)
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees AS E
        JOIN EmpCTE AS M
          ON E.mgrid = M.empid
    SELECT * FROM EmpCTE
    Using this level counter you can limit the number of iterations
     in the recursion. For example, the following CTE is used to return 
    all employees who are two levels below Janet:
    WITH EmpCTEJanet(empid, empname, mgrid, lvl)
    AS
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = 3
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees as E
        JOIN EmpCTEJanet as M
          ON E.mgrid = M.empid
      WHERE lvl < 2
    SELECT empid, empname
    FROM EmpCTEJanet
    WHERE lvl = 2
    As mentioned earlier, CTEs can refer to
     local variables that are defined within the same batch.
     For example, to make the query more generic, you can use 
    variables instead of constants for employee ID and level:
    DECLARE @empid AS INT, @lvl AS INT
    SET @empid = 3 -- Janet
    SET @lvl   = 2 -- two levels
    WITH EmpCTE(empid, empname, mgrid, lvl)
    AS
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = @empid
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees as E
        JOIN EmpCTE as M
          ON E.mgrid = M.empid
      WHERE lvl < @lvl
    SELECT empid, empname
    FROM EmpCTE
    WHERE lvl = @lvl
    Results generated thus far might be returned (but are not guaranteed to be), 
    and error 530 is generated. You might think of using the MAXRECURSION option 
    to implement the request to return employees who are two levels below 
    Janet using the MAXRECURSION hint instead of the filter in the recursive member
    WITH EmpCTE(empid, empname, mgrid, lvl)
    AS
      SELECT empid, empname, mgrid, 0
      FROM Employees
      WHERE empid = 1
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1
      FROM Employees as E
        JOIN EmpCTE as M
          ON E.mgrid = M.empid
    SELECT * FROM EmpCTE
    OPTION (MAXRECURSION 2)
    WITH EmpCTE(empid, empname, mgrid, lvl, sortcol)
    AS
      SELECT empid, empname, mgrid, 0,
        CAST(empid AS VARBINARY(900))
      FROM Employees
      WHERE empid = 1
      UNION ALL
      SELECT E.empid, E.empname, E.mgrid, M.lvl+1,
        CAST(sortcol + CAST(E.empid AS BINARY(4)) AS VARBINARY(900))
      FROM Employees AS E
        JOIN EmpCTE AS M
          ON E.mgrid = M.empid
    SELECT
      REPLICATE(' | ', lvl)
        + '(' + (CAST(empid AS VARCHAR(10))) + ') '
        + empname AS empname
    FROM EmpCTE
    ORDER BY sortcol
    (1) Nancy
     | (2) Andrew
     |  | (5) Steven
     |  | (6) Michael
     | (3) Janet
     |  | (7) Robert
     |  |  | (11) David
     |  |  |  | (14) James
     |  |  | (12) Ron
     |  |  | (13) Dan
     |  | (8) Laura
     |  | (9) Ann
     | (4) Margaret
     |  | (10) Ina
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to extend  breadth first Search for Binary Tree to any kind of Tree??

    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
    I have following code to successfully apply for breadth first Search in Binary Tree as follows,
    package a.border;
    import java.util.ArrayList;
    import java.util.LinkedList;
    public class Tree
        int root;
        Tree left;
        Tree right;
        static ArrayList<Integer> list = new ArrayList<Integer>();
        static ArrayList<Tree> treeList = new ArrayList<Tree>();
        private static LinkedList<Tree> queue = new LinkedList<Tree>();
         * @param root root value
         * @param left left node
         * @param right right node
        public Tree(int root, Tree left, Tree right)
            this.root = root;
            this.left = left;
            this.right = right;
        /** Creates a new instance of Tree
         * You really should know what this does...
         * @param root
        public Tree(int root)
            this.root = root;
            this.left = null;
            this.right = null;
         * Simply runs a basic left then right traversal.
        public void basicTraversal()
            //Check if we can go left
            if (left != null)
                left.basicTraversal();
            //Add the root
            list.add(root);
            //Check if we can go right
            if (right != null)
                right.basicTraversal();
        public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
            //Add the root to the arraylist, we know it is always the first entry.
            list.add(root);
            //Basically we add the first set of nodes into the queue for
            //traversing.
            //Query if left exists
            if (left != null)
                //Then add the node into the tree for traversing later
                queue.add(left);
            //Same for right
            if (right != null)
                queue.add(right);
            //Then we call the traverse method to do the rest of the work
            return traverse(list);
        private ArrayList<Integer> traverse(ArrayList<Integer> list)
            //Keep traversing until we run out of people
            while (!queue.isEmpty())
                Tree p = queue.remove();
                //Check if it has any subnodes
                if (p.left != null)
                    //Add the subnode to the back of the queue
                    queue.add(p.left);
                //Same for left
                if (p.right != null)
                    //Same here, no queue jumping!
                    queue.add(p.right);
                //Append to the ArrayList
                list.add(p.root);
            //And return
            return list;
         * Makes a tree and runs some operations
         * @param args
        public static void main(String[] args)
             *                             4
             *          t =           2       6
             *                      1   3    5   7
            Tree leaf6 = new Tree(1);
            Tree leaf7 = new Tree(3);
            Tree leaf8 = new Tree(5);
            Tree leaf9 = new Tree(7);
            Tree t4 = new Tree(2, leaf6, leaf7);
            Tree t5 = new Tree(6, leaf8, leaf9);
            Tree t = new Tree(4, t4, t5);
            t.basicTraversal();
            System.out.println("Here is basicTraversal ="+list.toString());
            list.clear();
            t.getBreadthTraversal(list);
            System.out.println("getBreadthTraversal= " +list.toString());
            list.clear();
        }Can Guru help how to update to any kind of tree??
    here this code is for the tree like:
             *                             4
             *          t =           2       6
             *                      1   3    5   7
             */But i hope the new code can handle tree like:
             *                             4
             *                           /   | \
             *                          /     |   \
             *          t =            2     8   6
             *                        / |  \    |    /| \
             *                      1 11  3 9   5 10  7
             */Thanks

    sunnymanman wrote:
    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
    What do all trees have in common? And what do all nodes in trees have in common?
    At least these things:
    interface Tree<T> {
        Node<T> getRoot();
    interface Node<T> {
        T getData();
        List<Node<T>> getChildren();
    }Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
    class BinaryTree<T extends Comparable<T>> implements Tree<T> {
        protected BTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class BTNode<T> implements Node<T> {
        private T data;
        private Node<T> left, right;
        public List<Node<T>> getChildren() {
            List<Node<T>> children = new ArrayList<Node<T>>();
            children.add(left);
            children.add(right);
            return children;
        public T getData() {
            return data;
    class NTree<T> implements Tree<T> {
        private NTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class NTNode<T> implements Node<T> {
        private T data;
        private List<Node<T>> children;
        public List<Node<T>> getChildren() {
            return children;
        public T getData() {
            return data;
    }Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
    interface Traverser<T> {
        List<Node<T>> traverse(T goal, Tree<T> tree);
    }And finally write an implementation for it:
    class BreathFirst<T> implements Traverser<T> {
        public List<Node<T>> traverse(T goal, Tree<T> tree) {
            Node<T> start = tree.getRoot();
            List<Node<T>> children = start.getChildren();
            // your algorithm here
            return null; // return your traversal
    }... which can be used to traverse any tree! Here's a small demo of how to use it:
    public class Test {
        public static void main(String[] args) {
            Tree<Integer> binTree = new BinaryTree<Integer>();
            // populate your binTree
            Tree<Integer> nTree = new NTree<Integer>();
            // populate your nTree
            Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
            // Look for integer 6 in binTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
            // Look for integer 6 in nTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
    }Good luck!

  • Creation of a Popup Menu for a Tree Node

    Hi Ppl,
      I need to create a Pop-up Menu for a tree node in WebDynpro Application, please give me a "How to .." sort of material or a link which would have same sort of information...
    Also, My requirement is to call the pop-up on the right click of mouse on the tree node, please let me know on which event handler I can call it ? Do I require a custom event handler for it ?
    Thanks in advance
    Anish

    Hi Anish,
    You simply add a Tree UI element, and then right-click the tree UI element and insert a TreeNode element.
    To the TreeNode element you can add a menu, and then to this menu you can add menu items. When the user right click the tree node, the menu item is displayed. If the user clicks the menu item, the action for the menuitem is run.
    Hope that helps.
    Daniel

  • How to design  databse for binary tree

    kindly help in desiging databse for binary tree and also to retrive data from database.

    Since you're not asking about Java, you'll probably get more responses by posting this in a database forum.

  • Succinct encoding for binary tree with n nodes...

    How do I find all possible bit strings (Succinct encoding) for a binary tree with order n? Can anybody give me an algorithm?

    I associate the order of a tree with some sort of a search or traversal. What do you mean by a "+tree with order n+"?
    Could you perhaps give an example of what you're looking for?

  •      Need coordinate for particular tree node as currently expanded

    Hi All,
    i am working in flex for the past two months,currently i am
    working on the drag and drop on a tree , where i am able to drag
    one tree leaf node to another another tree leaf node and i am able
    to draw a line between the two leaf node indicating that this has
    been dragged from the previous tree of a particular node to the
    current node of the tree.
    The problem which i am facing is that when i collapse the
    expanded tree , the line which i have drawn is not able to
    synchronize with the tree expand or collapse (the line remains in
    the same position even when the particular leaf node move down coz
    of expansion of the above tree node.)
    any help will be appreciated.

    there is a private function in the tree.as class:
    private function getVisibleChildrenCount(item:Object):int
    that I can use by multiplying how many children there are by
    how tall each item "physically" displays on the screen as, but I
    want to get that publicly. I don't want to go about hacking the
    tree.as code, that's poor form in the highest. Does anybody else
    have any ideas...
    please?

  • Help for Activating Editing Mode on F2 Keyboard Click for a Tree Node

    I have a Jtree with several Nodes on the Left Pane. On the Right Pane I have a nodes corresponding Screen with many properties. There is a way to change the Node Name by editing the Name Field property on the Right.
    I want to Edit the tree Node name by Clicking F2 on the selected Node, Get it in the Editable Mode, Change the name and press enter. How Do I activate this editable Mode on Click of Keyboard F2 Button.

    tree.setEditable( true );

  • JTree: How to set different cell editor for different tree Nodes.

    I have a JTree and I want to set different cell editors for different node depending on some condition. E.g. I want to set ComboBox as editor for leaf node but each leaf node will have its own set of data.
    Any help or pointer?
    Thanks in advance
    Sachin

    take there:
    http://www.mutualinstrument.com/Easy/FAQ/Tree/tree.html

  • Setting Background Color for a tree node

    I have the following code
    ====================================================================================
    public class IconNodeRendererClass extends DefaultTreeCellRenderer {
    //* getListCellRendererComponent
    /**Return a component renderer based on the passed in components*/
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean sel, boolean expanded, boolean leaf,
    int row, boolean hasFocus) {
    Component c = super.getTreeCellRendererComponent(tree, value,
    sel, expanded, leaf, row, hasFocus);
    ImageIcon icon = ((IconNodeClass)value).getIcon();
    if (((IconNodeClass)value).isRoot()) {
    c.setBackground(Color.blue);
    setIcon(null);
    return c;
    if (icon != null) {
    setIcon(icon);
    return this;
    }// end getTreeCellRendererComponent
    }// end IconNodeRendererClass
    ====================================================================================
    I would like to have a gray color to the root node before even I selected the root node.
    Can I do that by setting the background color?
    With the below code I am unable to set the background color to the root node even when I selected it. what else can i write to set the color to the root node?
    if (((IconNodeClass)value).isRoot()) {
    c.setBackground(Color.blue);
    setIcon(null);
    return c;

    I gave the following on your advice. But the background color is set to all the nodes. I want it to be set it to only the root node. How can I do that? Thanks.
    if (((IconNodeClass)value).isRoot()) {
    setOpaque(true);
    c.setBackground(Color.gray);
    updateUI();
    setIcon(null);
    }

  • Like to see few real life usage of Binary Tree C#

    whenever we read something about BTree then this kind of program shown in article with code.
    code as follows.
    Main File
    static void Main(string[] args)
    //Creating the Nodes for the Tree
    Node<int> tree = new Node<int>('6');
    tree.Left = new Node<int>('2');
    tree.Right = new Node<int>('5');
    Console.WriteLine("Binary Tree Display");
    Console.WriteLine(tree.Data);
    Console.ReadLine();
    Node Class
    class Node<T> where T : IComparable
    private T data;
    public Node<T> Left, Right;
    public Node(T item)
    data = item;
    Left = null;
    Right = null;
    public T Data
    set { data = value; }
    get { return data; }
    in our daily program where we can use btree to store and retrieve data? so please all share your idea how you guys use btree in your program in real life application development. thanks

    "in our daily program where we can use btree to store and retrieve data?"
    Given that your example mentions IComparable I suppose you're talking specifically about binary search trees, not any binary tree. In that case it's unlikely that you'll see anyone using a binary tree directly. People use collections such as SortedDictionary and
    such collections are usually implemented using binary search trees.
    Note that btree isn't a good abbreviation for binary tree, there is such a data structure called B-Tree and it's not the same thing as binary tree. Incidentally B-Trees are also used for searching - databases use them for indexes and filesystems
    use them to store directory entries.
    @Joel Engineer: "Binary trees structures are built into the Net Library Hash Class"
    Binary trees and hash tables have nothing in common.

  • Binary Tree Search

    Hi everyone,
    I have an assignment :Implement a binary search tree class. Include preOrder, inOrder, postOrder traversals, as well as methods to perform insert and search.
    And I did it in the folloiwng but there some problems that I encounter.When I execute the following code, there is an exception occurs. It says that my left BinaryTree is null. So why ???
    Implement a binary search tree class. Include preOrder, inOrder, postOrder traversals, as well as methods to perform insert and search

    Hi,
    I changed the old codes to the below. I think this is orrect logically for binary trees.
    If not, please explain why ??
    import java.util.*;
    class BinaryTree {
         // properties
         ArrayList store;
         BinaryTree left;
         BinaryTree right;
         int root;
         int valuesLeft = 1;      // for adding the left root
         int valuesRight = 1;     // for adding the right root
         // constructors
         // first constructor
         public BinaryTree(BinaryTree left, BinaryTree right){          
              store = new ArrayList();
              root = 12;
              store.add( new Integer(root));  // root value
              this.left = left;
              this.right = right;
         // second constructor
         public BinaryTree(){
              store = new ArrayList();
         // methods
         public void insert(int a){
              if(a < ( (Integer)(store.get(0)) ).intValue()){
                   setLeft(a);
              else{
                   setRight(a);
         public void setLeft(int node){
              if(valuesLeft == 1)
                   root = node;
              (left.store).add(new Integer(node) );
              valuesLeft++;
         public void setRight(int node){
              if(valuesRight == 1)
                   root = node;
              (right.store).add(new Integer(node) );
              valuesRight++;
         public int search(int value){
              if(value == root){
                   return value;
              else if(value < root){
                   return left.search(value);
              else if(value > root)
                   return right.search(value);
              else
                   return -1;     
    //     public String toString(){
         public static void main( String[] args)
              BinaryTree leftTree = new BinaryTree();
              BinaryTree rightTree = new BinaryTree();
              BinaryTree root = new BinaryTree(leftTree, rightTree);
              root.insert(5);     
              root.insert(15);
              root.insert(6);          
              root.insert(3);          
              root.insert(51);
              root.insert(2);     
              root.insert(115);
              root.insert(7);          
              root.insert(33);          
              root.insert(511);               
              root.search(15);     
    }

  • Tree and Tree Node Components - Threadinar7

    Hi All,
    This is the seventh in the "Threadinar" series , please see Threadinar6 at
    http://forum.sun.com/jive/thread.jspa?threadID=100601 for details
    In this Threadinar we will focus on the
    "Tree" and "Tree Node" Components
    Let us begin our discussion with the Tree Component.
    Tree Component
    You can drag the Tree component from the Palette's Basic category to the Visual Designer to create a hierarchical tree structure with nodes that can be expanded and collapsed, like the nodes in the Outline window. When the user clicks a node, the row will be highlighted. A tree is often used as a navigation mechanism.
    A tree contains Tree Node components, which act like hyperlinks. You can use a Tree Node to navigate to another page by setting its url property. You can also use a Tree Node to submit the current page. If the the Tree Node's action property is bound to an action event handler, selecting the node automatically submits the page. If the Tree Node's actionListener property is bound to an action listener, opening or closing the node automatically submits the page. You set Tree Node properties in the Tree Node Component Properties window.
    * If you use this component to navigate between pages of a portlet, do not use the url property to link to a page. Instead, use the Navigation editor to set up your links to pages.
    * Events related to tree node selection do not work correctly in portlets because the component uses cookies to pass the selected node id back and forth, and cookies are not correctly handled by the portlet container. You cannot handle tree node selection events in portlet projects.
    Initially when you drop a tree on a page, it has one root node labeled Tree and one subnode labeled Tree Node 1. You can add more nodes by dragging them to the tree and dropping them either on the root node to create top level nodes or on existing nodes to create subnodes of those nodes. You can also right-click the Tree or any Tree Node and choose Add Tree Node to add a subnode to the node.
    Additionally, you can work with the component in the Outline window, where the component and its child components are available as nodes. You can move a node from level to level easily in the Outline window, so you might want to work there if you are rearranging nodes. You can also add and delete tree nodes in the Outline window, just as in the Visual Designer.
    The Tree component has properties that, among other things, enable you change the root node's displayed text, change the appearance of the text, specify if expanding or collapsing a node requires a trip to the server, and specify whether node selection should automatically open or close the tree. To set the Tree's properties, select the Tree component in your page and use the Tree Component Properties window.
    The following Tutorial ("Using Tree Component") is very useful to learn using Tree components
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/sitemaptree.html
    See Also the Technical Article - "Working with the Tree Component and Tree Node Actions"
    http://developers.sun.com/prodtech/javatools/jscreator/reference/techart/2/tree_component.html
    Tree Node Component
    You can drag the Tree Node component from the Palette's Basic category to a Tree component or another tree node in the Visual Designer to create a node in a hierarchical tree structure, similar to the tree you see in the Outline window.
    The tree node is created as a subnode of the node on which you drop it. If you drop the node on the tree component itself, a new node is created as a child of the root node. You can see the hierarchical structure clearly in the Outline window, where you can also easily move nodes around and reparent them.
    You can also add a tree node either to a Tree component or to a Tree Node component by right-clicking the component and choosing Add Tree Node.
    A Tree Node component by default is a container for an image and can be used to navigate to another page, submit the current page, or simply open or close the node if the node has child nodes.
    * If you select the Tree Node component's node Tree Node icon in the Outline window, you can edit its properties in the Tree Node Properties window. You can set things like whether or not the Tree Node is expanded by default, the tooltip for the Tree Node, the label for the tree node, and the Tree Node's identifier in your web application.
    * You can use a Tree Node to navigate to another page by setting its url property. You can also use a Tree Node to submit the current page. If the the Tree Node's action property is bound to an action event handler, selecting the node automatically submits the page. If the Tree Node's actionListener property is bound to an action listener, opening or closing the node automatically submits the page.
    - Note: If you use this component to navigate between pages of a portlet, do not use the url property to link to a page. Instead, use the Navigation editor to set up your links to pages. In addition, events related to tree node selection do not work correctly in portlets because the component uses cookies to pass the selected node id back and forth, and cookies are not correctly handled by the portlet container. You cannot handle tree node selection events in portlet projects.
    * If you select the image in the Tree Node, you can see that its icon property is set to TREE_DOCUMENT. If you right-click the image on the page and choose Set Image, you can either change the icon to another one or choose your own image in the Image Customizer dialog box. For more information on working with an image in a tree node, see Image component.
    - Note: The image used in a tree node works best if it is 16x16 or smaller. Larger images can work, but might appear overlapped in the Visual Designer. You can right-click the component and choose Preview in Browser feature to check the appearance of the images.
    Please share your comments, experiences, additional information, questions, feedback, etc. on these components.
    ------------------------------------------------------------------------------- --------------------

    One challenge I had experience was to make the tree
    always expanded on all pages (I placed my tree menu
    in a page fragment so I can just import it in my
    pages).Did you solve this problem. It would be interesting to know what you did.
    To expand a node you call setExpanded on the node. Here is some code from a tutorial that a coworker of mine is working on.
    In the prerender method:
           Integer expandedPersonId = getRequestBean1().getPersonId();
             // If expandedPersonId is null, then we are not coming back
            // from the Trip page. In that case we do not want any trip
            // nodes to be pre-selected (highlighted) due to browser cookies.
            if (expandedPersonId==null) {
                try {
                    HttpServletRequest req =(HttpServletRequest)
                    getExternalContext().getRequest();
                    Cookie[] cookies = req.getCookies();
                    //Check if cookies are set
                    if (cookies != null) {
                        for (int loop =0; loop < cookies.length; loop++) {
                            if (cookies[loop].getName().equals
                                    ("form1:displayTree-hi")) {
                                cookies[loop].setMaxAge(0);
                                HttpServletResponse response =(HttpServletResponse)
                                getExternalContext().getResponse();
                                response.addCookie(cookies[loop]);
                } catch (Exception e) {
                    error("Failure trying to clear highlighting of selected node:" +
                            e.getMessage());
            }                  ... (in a loop for tree nodes)...
                      personNode.setExpanded(newPersonId.equals
                                    (expandedPersonId));In the action method for the nodes:
           // Get the client id of the currently selected tree node
            String clientId = displayTree.getCookieSelectedTreeNode();
            // Extract component id from the client id
            String nodeId = clientId.substring(clientId.lastIndexOf(":")+1);
            // Find the tree node component with the given id
            TreeNode selectedNode =
                    (TreeNode) this.getForm1().findComponentById(nodeId);
            try {
                // Node's id property is composed of "trip" plus the trip id
                // Extract the trip id and save it for the next page
                Integer tripId = Integer.valueOf(selectedNode.getId().substring(4));
                getRequestBean1().setTripId(tripId);
            } catch (Exception e) {
                error("Can't convert node id to Integer: " +
                        selectedNode.getId().substring(4));
                return null;
    It would also be great if I can set the tree
    readonly where the user cannot toggle the expand
    property of the tree (hope this can be added to the
    tree functionality).

  • Determine if mouse is over tree node

    hi.
    I recently added some code from this forum on
    highlighting a node when the mouse is over it.
    I am taking this futher and setting a Border around the nodehowever it draws a border around every node.
    I want to only draw the border when the mouse is over the node.
    the example i got does this to set the foreground
    ((JLabel)result).setForeground(Color.red);
    i do this to set the border
    ((JLabel)result).setBorder
    (BorderFactory.createLineBorder(Color.black));
    i ve tried getting the positions of both the mouse and the jlabel but am having trouble determining if the position of the mouse is within the position of the node in the tree.
    Ive used methods like the contains method but it doesnt work for me . can anyone give me a hint as to how to see if the points of the mouse are on the Jlabel?

    This is very close to your solution. Last month, I implement ToolTip Text on every Tree Node so when Mouse goes on to the Node, It shows the Tool Tip Text. Have a look at this code and try to change it accordingly.
    This code is in the Constructor in your class.
    tree.setCellRenderer(new IDETreeCellRenderer());
    tree.setToolTipText("");Class: IDETreeCellRenderer - Cell Renderer for the Tree
    package tv.izone.ide.tree;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import tv.izone.core.*;
    import tv.izone.ide.guiutilities.*;
    import tv.izone.izml.data.*;
    public class IDETreeCellRenderer
        extends DefaultTreeCellRenderer {
       DefaultTreeCellRenderer label;
        * Override TreeCellRendererComponent, used for changing Tree Node for comments.
        * @param tree Tree to be used
        * @param value Value of the Node
        * @param selected true, if selected
        * @param expanded true, if expanded
        * @param leaf true, if it is a leaf
        * @param row Row Number
        * @param hasFocus True, if has Focus
        * @return Component, Tree
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
                                      boolean leaf, int row, boolean hasFocus) {
          try {
          label = (DefaultTreeCellRenderer)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
                                                      hasFocus);
          label.setToolTipText(dataObject.getToolTipText());
    // Instead of setToolTipText(), try setBackgroundColor() or setBorder()
         return label;
          } catch (Exception ex) {
          // NullPointerException, usually comes at the start of the Application
          // when the Tree is empty.
          return this;
    }Hope this Helps
    Regards
    Raheel

  • How to directly change the text of a tree node once its in the tree

    How can I directly change the text of a tree node once its in the tree.
    I have a property box which fires an eventevery time it is edited
    (this is currently just output to the screen via println)
    What i want is for the tree node to take the updated text that is in the text box every time
    thus giving tree labels that update as you type
    PS. i have access to the tree node (DefaultMutableTreeNode) from the code that hanldes
    the text box event

    ... use the setUserObject() method of your DefaultMutableTreeNode, that'll set the text of the node.
    however, you probably need to do a treeModel.nodeChanged(node) with your tree model, to get the display updated.
    thomas

Maybe you are looking for

  • Re-downloads of music through iTunes app interrupts music on iPhone.

    When I go to download purchased music through the iTunes app, every time a song finishes downloading, the sound of music playing drops out for a second. Half the time the music stops playing all together and I have to go and re-hit play. The dropout

  • ALE from 5.0 to 4.6C - missing Segment in HRMD_A05

    I'm using a the ALE Interface to transfer Org.Management-data between a 5.0 and a 4.6c HCM (HR) System. It worked well between two 4.6c Systems using the Basic Type HRMD_A05. Unfortunatly the structure for infotype 1001 subtype *007 (Link between [S]

  • Security preference keeps unlocking

    Not sure what is going on here. In system preferences I have my Accounts settings locked as well as my network and sharing and security settings too. But every time after I shut down or restart the security settings are unlocked? What gives? Is it so

  • I can´t use itunes store. nothing shows. no error, nothing. its just all white,

    there´s nothing in there like it was empty i double check conections. also i can listen radios and every other function. but itunes store, is dead any ideas?

  • WD Model?

    Hi, I'm familiar with DS 7.0, and I'm begining to lear 7.1 recently. I searched for tutorials and in the forum, but I can't find how to create a Web Dynpro model from a CAF DC, in 7.0 it was just a right click and generate WD Model, can you help me p