JTree from DefaultMutableTreeNode

Hi all,
I am not sure of this. I have DefaultMutableTreeNode refrence of a JTree.
There are lot of trees and DefaultMutableTreeNode instances are different for each JTree.
Is it possible to get the JTree reference from DefaultMutableTreeNode
Thanks,
sur.

you need to cast the child to a DefaultMutableTreeNode before you can get the user object

Similar Messages

  • Build a JTree from data

    Hello everyone,
    I have to build a JTree from a table data from database. The table structure is
    (id,parent_id,name). In order to build the tree, I have to the following 2 loop searching for the parent_id
    while (i<size){
    while(j<size){
    //find it's parent_id
    j++;
    i++;
    It is too slow! Can anyone help me?
    Thanks!
    --tc                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    You just add children to whatever the parent node is for that object.DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    child1 = new DefaultMutableTreeNode();
    root.add( child1 );
    grandChild = new DefaultMutableTreeNode();
    child1.add( grandChild );
    greatGrandChild = new DefaultMutableTreeNode();
    grandChild.add( greatGrandChild );Etc.

  • Populating JTree from database

    Hi experts,
    I need some feedbacks about the way i populate my JTree from database, Is there any better alternatives?
    If yes, try explain it in detail.. I'm still new in Java.
    Sample database table:
    |       node_id      |       name      |       parent       |       hasChild      |
    |         1          |     garbage     |        null        |           1         |
    |         2          |       item      |          1         |           1         |
    |         3          |      mouse      |          2         |           0         |
    |         4          |       board     |          2         |           0         |
    |         5          |       item2     |          1         |           1         |
    |         6          |       item3     |          1         |           1         |
    |         7          |       pants     |          5         |           0         |
    -----------------------------------------------------------------------------------Here's the sample of my code:
    //... ResultSet rs = .....
    rs.last();
    int rowCount = rs.getRow(); //Get the total number of row in database table
    rs.beforeFirst();
    int i = 0;
    int j = 0;
    String [] nodeID = new String[rowCount];  //The node ID
    String [] parentID = new String[rowCount];  //A pointer to its parent ID
    DefaultMutableTreeNode [] node = new DefaultMutableTreeNode[rowCount]; //The node
    while(rs.next()) {
         String name = rs.getString("name");
         Boolean bool = rs.getBoolean("hasChild");
         node[i] = new DefaultMutableTreeNode(name,bool);
         parentID[i] = rs.getString("parent");
         nodeID[i] = rs.getInt("node_id") + "";
            //Set as root node when the pointer is null               
         if(parentID.equals("null")) {
              rootNode = node[i];
         i++;
    for(i=0; i<rowCount; i++) {
         for(j=0; j<rowCount; j++) {
              if(parentID[j].equals(nodeID[i]) && node[i] != null) {
                   node[i].add(node[j]);
    node[i] = null; //Obligates the parent after finish adding the child (to prevent unnecessary loops)
    //... tree = new JTree(rootNode);
    Thanks for the trouble,
    Regards,
    David

    The execution time are base on the code i post'ed here.
    Average over 30times using Vector = 640048 nanosecond to execute.
    Vector<String> nodeID = new Vector<String>();
    Vector<DefaultMutableTreeNode> node = new Vector<DefaultMutableTreeNode>();
    Vector<String> parentID = new Vector<String>();
    rs.last();
    int rowCount = rs.getRow();
    rs.beforeFirst();
    k=0;
    while(rs.next()) {
         String name = rs.getString("name");
         Boolean hasChild = rs.getBoolean("hasChild");
         node.addElement(new DefaultMutableTreeNode(name,hasChild));
         nodeID.addElement(rs.getInt("node_id")+"");
         parentID.addElement(rs.getString("parent"));
         if(parentID.elementAt(k).equals("null")) {
              rootNode = node.elementAt(k);
         k++;
    i=0;
    while(i<rowCount) {
         j=0;
         while(j<rowCount) {
              if(parentID.elementAt(j).equals(nodeID.elementAt(i)) && node.elementAt(j) != null) {
                   node.elementAt(i).add(node.elementAt(j));
                   if(!node.elementAt(i).getAllowsChildren())
                        node.insertElementAt(null,j);
              j++;
         i++;
    }Average over 30times using LinkedList = 95623 nanosecond to execute.
    //This section will have a class Nodes
    LinkedList<Nodes> gather = new LinkedList<Nodes>();
    while(rs.next()) {
         node = new DefaultMutableTreeNode(rs.getString("name"),rs.getBoolean("hasChild"));                    
         gather.add(new Nodes(rs.getInt("node_id") + "",node,rs.getString("parent")));
    for(Nodes findParent : gather) {                    
         if(findParent.getParentID().equals("null")) {
              findParent.setRoot(findParent.getNode());
              rootNode = findParent.getRoot();
         for(Nodes findChild : gather){
              if(findChild.getParentID().equals(findParent.getNodeID()))
                   findParent.getNode().add(findChild.getNode());               
    }As for the Array method i used from the previous post, the Average code execution time is x3 larger than the vector i used. So please do not use that method.
    Note: 1. The code i post can be improved further. 2. Execution time is based on individual computer.
    Well, I think i'll stop here. Anyone who wanted to know which method is more efficient currently, here's the answer.
    Hope that it helps anyone who have the problem here =).
    Edited by: DavidTW on May 23, 2011 3:14 PM
    Improved Version : Using for-each loop ( Effective Java, Second Edition, Joshua Bloch, Pg. 210).

  • JTree from vector

    Hi there, i have looked back through the forums and at the JTree tutorial, and i have seen people mention about constructing a JTree from a vector.i can do this from a DefaultMutableTreeNode but how can one construct a JTree from a vector?.i have also seen from the api that you can supply a vector as an argument for the JTree constructor, but how does the JTree construct the tree from thia particular vector?many thanks.

    but how does the JTree construct the tree from thia particular vector?Take a look at the JTree source code.

  • Creating dynamically JTree from database values

    Hi,
    I have a local database with some node values. I receive these values from database as a String[].
    short example:
    String[] Values = {"mainNode","Processors","mainNode","RAM","mainNode","Monitors",
    "Processors","INTEL","Processors","AMD","RAM","Kingston","RAM","GoodRAM",
    "Kingston","400MHz","Kingston","433MHz"}First value is higher node, second is a child.
    I'd like to produce dynamically JTree from Values[] like below:
    MainNode
    |----Processors
          |----INTEL
          |----AMD
    |----RAM
          |----Kingston
                |----400MHz
                |----433MHz
          |----GoodRam
    |----MonitorsI can't build up any working and fast solution :(
    Can anyone help me ?
    Please for any advices (samples) which will help me to apply it.
    Dearly regards!

    This is a relatively straight forward task but it smacks of being homework so unless you post what you have already done you are unlikely to be given any code.
    As a hint -
    Go through the data creating a Map between the parent value and a child DefaultMutableTreeNode which contains as user object the child String.
    When you extract a parent String from the data lookup the parent DefaultMutableTreeNode in the map and add the child DefaultMutableTreeNode to the parent DefaultMutableTreeNode.
    Note - All the map is doing is giving you a quick way of looking up a DefaultMutableTreeNode given a parent name.
    Note - that your tree will have problems if the same value appears in two or more branches!

  • How can i refresh a jtree using DefaultMutableTreeNode?

    I already create a jtree using DefaultMutableTreeNode, and i also could implement to it the addMouseListener to do a action when the user press every node......Also i used the following instruction to remove all nodes: root_tree.removeAllChildren(); and it instruction remove all the nodes....but when i :
    fill the tree
    compile my program
    i see the tree in my jpanel....it is Ok!
    now.....
    fill the tree
    remove the tree
    compile my program
    i see only the root (this i wish) it is Ok!
    But now i would like that after that i press a combo element (in the actionperformed method):
    remove the tree
    fill the three with the new nodes
    show the tree
    But my tree always is the same :(......is like it to need a repaint ....but i already implement it...but i obtain the same result.....
    Do somebody have any suggestion...or idea how i can do a refresh in my jtree?....
    Anybody could help me please?
    Thanks in advance.....
    Mary

    Construct your tree like this:DefaultMutableTreeNode rootNode = xxx;
    DefaultTreeModel model = new DefaultTreeModel( rootNode );
    JTree tree = new JTree( model );When you update the root node, just tell the model to fire the appropriate change event by doing this:model.reload( rootNode );or this:model.nodeStructureChanged( rootNode );or this:model.setRoot( rootNode )

  • Building jtree from database query

    I am trying to build a JTREE from a database result-set. The resultset is listed below. I'm thinking I can somehow build a dynamic array of objects to build a TreePath, then use that to build the JTREE. Any input is appreciated.
    ResultSet Output:
    Here is how the results would be retrieved from the database (including the order of the output).
    usr 1
    local 2
    sbin 2 file4
    bin 3 file1
    bin 3 file2
    logs 3 file3
    tmpdir 4
    The first column is the directory name, the second column is the directory/file level/position, and the third column is the filename, if one exists.
    So from above:
    /usr/local/sbin has file "file4"
    /usr/local/bin has files "file1" and "file2"
    /usr/local/logs has file "file3" and directory "tmpdir"
    How could I gather this information into an appropriate structure and create a JTREE from it.
    Thanks.
    -Jim

    So each line would:basically...
    If I don't know the entire path of the parent (because I've read in a
    line that only has the "one-up" parent name) .... However, when I
    read the line from the database result-set, I don't know where "local" is.See... that's another problem with that data. Maybe you know cuz it's the last node if it's all in a proper order. In which case maybe you only need to hold the last parent node... Some recursive function would be useful.
    If I were going to store the data, I would store either the name as a full path:
    /usr
    /usr/local
    /usr/loca/bin
    or
    usr /
    local /usr
    bin /usr/local
    If you have that, it might be easier to figure out without having to worry about what belongs where.

  • How to set selected JTree from outside?

    I have a JTree for example
    -A
      -a
      -b
      -c
    -B
      -a
      -b
      -c
    -C
      -a
      -b
      -cif the tree is All expand , it is easy to select the the tree by setSelectionRow(5), the result is "B.a", but how to select the the tree if all collap
    -A
    -B
    -C
    {code}
    let say i want to select "B.c", it can't use setSelectionRow(7) becouse the row between 0-2. So how to select the tree if the tree is *collap*?
    thx..                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    i had try use setSelectionPath but still can't wotk
    this sample code:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JTree;
    import javax.swing.tree.*;
    import javax.swing.*;
    public class test_tree extends JFrame{
        JTree tree;
        DefaultMutableTreeNode root_tree;
        test_tree(){
            //DefaultMutableTreeNode root_tree = new DefaultMutableTreeNode("Root",true);
            root_tree = new DefaultMutableTreeNode();
            DefaultMutableTreeNode child_tree;
            DefaultMutableTreeNode child_tree2;
            DefaultMutableTreeNode child_tree3;
            child_tree = new DefaultMutableTreeNode("A1",true);
            child_tree.add(new DefaultMutableTreeNode("A1.1",false));
            child_tree.add(new DefaultMutableTreeNode("A1.2",false));
            child_tree.add(new DefaultMutableTreeNode("A1.3",false));
            child_tree2 = new DefaultMutableTreeNode("B2",true);
            child_tree2.add(new DefaultMutableTreeNode("B2.1",false));
            child_tree2.add(new DefaultMutableTreeNode("B2.2",false));
            child_tree2.add(new DefaultMutableTreeNode("B2.4",false));
            child_tree3 = new DefaultMutableTreeNode("C3",true);
            child_tree3.add(new DefaultMutableTreeNode("C3.1",false));
            child_tree3.add(new DefaultMutableTreeNode("C3.2",false));
            child_tree3.add(new DefaultMutableTreeNode("C3.3",false));
            root_tree.add( child_tree);
            root_tree.add( child_tree2);
            root_tree.add( child_tree3);
            tree = new JTree(root_tree);
            tree.setRootVisible(false);
            tree.setSize(100,300);
            add(tree);
            JButton bt = new JButton("witPath");
            bt.setSize(new Dimension (80, 30));
            bt.setLocation(200,100);
            bt.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    tree.expandPath(new TreePath(root_tree.getNextNode().getChildAt(1)) );
                    tree.setSelectionPath(new TreePath(root_tree.getNextNode().getChildAt(1)) );
            add(bt);
            JButton br = new JButton("witROW");
            br.setSize(new Dimension (80, 30));
            br.setLocation(200,150);
            br.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    tree.expandRow(1);
                    tree.setSelectionRow(3);
            add(br);
            setSize(400,400);
            setLayout(null);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public static void main(String args[]){
                new test_tree();
    }thx..

  • JTree from root

    If a TreeNode has been set as the root of a JTree, is there any method that will recover the JTree from the TreeNode (other than just coding the info into the program's data when you set the node as root)?

    I managed to come up with a pair of jtree/node classes that do what I want, e.g. node.addNotify(newChild) causes the jtree display to update; I think this is better than node.add(newChild);<something update the jtree display> on the basis that `an intelligent object moves complexity from the many to the few'(Cline & Lomow _C++ FAQS+ p 42).  I'm just surprised that this isn't made easier to do.

  • JTree from Hashtable: weird ordering

    Need some help on this:
    I am making a JTree from a Hashtable:
    myJTree = new JTree(myHashtable);The elements are put in the hashtable in the right order, but they come out in the GUI all wrong, can't seem to see any logic behind the order.
    The children are not supposed to be sorted alphabetically, but in the order I get from an XML file. They are put in the Hashtable one by one.
    Any ideas?

    They are not sorted by key or value. But they are put in the hashtable in a specific order, the same order as they are in a XML file. And I need it to be in a data structure I can use to create a JTree.
    I tried to put the items in a vector. The order was then correct. The problem is that I then loose info (<key, value>) from the hashtable. And I cant get more than one level in the tree from the JTree(vector) constructor.
    So what do I do?
    To make it more clear how my tree looks like:
    ___Root object _nr1 (object in xml)
    |
    |________Child (first subcomponent in xmll)
    |
    |________Child (second subcomponent in xmll)
    |
    |________Child(third subcomponent in xmll)
    |
    etc.
    Its as simple as that

  • Jtree from database

    hii all,
    Does any one know hw to populate a Jtree from a database.pls hlep me with an example.
    thanx

    Hi there,
    Im having exactly the same problem. If you find out, please let me know, and I will do the same for you.
    Thanks
    Simon

  • Getting TreePath from DefaultMutableTreeNode

    Hi,
    I am looking through the APIs and I haven't found a way in which I can get the TreePath of a specific DefaultMutableTreeNode. In the class that I am trying to get this value I have the reference to the JTree in which the node is located, and a reference to the node itself.
    Please let me know if there is a way to get this value...
    P.S. I need this value, to set the JTree focus on the node. So, if you have a solution for that as well, without using the TreePath, it would be of great value also.
    Thankx
    Juan

    Well, just in case someone is watching this post...
    I found a way, it may not be the best but here it goes;
    public void setFocus(JTree tree, DefaultMutableTreeNode node) {
         DefaultMutableTreeNode parent= null;
         int nodeLevel= node.getLevel();
         int indx= 0;
         for( int i= 1; i < nodeLevel; i++ ) {
              parent= (DefaultMutableTreeNode)node.getParent();
              indx+= parent.getIndex(node)+1;
              node= parent;
         tree.setSelectionRow(indx);
         tree.requestDefaultFocus();
    }

  • Removing a JTree from a JScrollPane

    I am working with an awt Applet but i need to use a JTree.
    When the user press a button a need to remove the JTree from its container but it doesn't work
    I try this:
    jscroll.remove(jtree);
    jscroll.updateUI();
    jtree = null;
    repaint();
    Can anybody help me, please.

    Thank you.
    Another question:
    I have a jtable with multiple spanded cells. I am using a custom jtable(the code is in http://www2.gol.com/users/tame/swing/examples/JTableExamples4.html) but i need insert a new row when you click on a button.
    I doing this:
    jtable.getModel().addRow(vector);
    but it throws an exception:
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 11 >= 11
         at java.util.Vector.elementAt(Unknown Source)
         at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
         at javax.swing.JTable.getValueAt(Unknown Source)
         at javax.swing.JTable.prepareRenderer(Unknown Source)
         at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paintCell(MultiSpanCellTableUI.java:96)
         at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paintRow(MultiSpanCellTableUI.java:68)
         at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paint(MultiSpanCellTableUI.java:39)
         at javax.swing.plaf.ComponentUI.update(Unknown Source)
         at javax.swing.JComponent.paintComponent(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JComponent.paintChildren(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JViewport.paint(Unknown Source)
         at javax.swing.JComponent.paintChildren(Unknown Source)
         at javax.swing.JComponent.paint(Unknown Source)
         at javax.swing.JComponent.paintWithBuffer(Unknown Source)
         at javax.swing.JComponent._paintImmediately(Unknown Source)
         at javax.swing.JComponent.paintImmediately(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Can anybody help me

  • Building JTrees from Filename strings????

    Does anybody know or have code to build JTrees from fileName string so that the tree is expandable and uses expansion listeners.

    Does anybody have code that allows you to show the local filesystem and also file strings contained say in a file so they can both be viewed at the same time. ie if you know somebody else has a file but you want it reflected in your local filesystem.
    Come on somebody must

  • Confusion building JTree from path strings

    If I have a bunch of strings like this:
    "/dira/dir1/file1"
    "/dira/dir1/file2"
    "/dira/dir2/file1"
    "/dira/dir3/anotherdir/file1"
    etc.
    Does anybody have an easy solution to getting them in a JTree that looks like this:
       dira
        |
        +-dir1
        |  |
        |  +-file1
        |  |
        |  +-file2
        |
        +-dir2
        |  |
        |  +-file1
        |
        +-dir3
           |
           +-anotherdir
              |
              +-file1Mainly I am having trouble getting the tree to populate without duplicating nodes. For example dir1 gets listed twice. I am looking for a solution that will parse these strings and build the tree. I have found demos that read a file system, but nothing that works with strings. I have tried to pick apart the file system demos, but so far I can't get it to work correctly.
    Thanks,
    Jeff

    This compiles and works (with 1.4):
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.HashMap;
    public class TreeStrings extends JFrame {
        public TreeStrings() {
            super("Tree strings");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(500, 400);
            String[] inputStrings = {"/dira/dir1/file1", "/dira/dir2/file1", "/dira/dir2/file2"}; // your bunch of Strings     
         DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("www");
         HashMap nodeMap = new HashMap();
         for(int i = 0; i < inputStrings.length; i++) {
             String s = inputStrings;
         DefaultMutableTreeNode lastNode = rootNode;
         int lastIndex = 0;
         while(true) {
              DefaultMutableTreeNode tempNode = null;
              int nextIndex = s.indexOf("/", lastIndex + 1); // <- i forgot + 1
              if(nextIndex != -1) { //we are somewhere in middle of s, checking nodes from root to leaf, one by one.
         String nodeKey = s.substring(0, nextIndex);
         if(nodeMap.get(nodeKey) == null) { //no such node, must make one
              String nodeName = s.substring(lastIndex, nextIndex); // you want the last nodeKey word for node name
         DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeName);
         nodeMap.put(nodeKey, newNode);
         lastNode.add(newNode);
         lastNode = newNode;
         else { //allready such node, just put it to be lastNode
         lastNode = (DefaultMutableTreeNode) nodeMap.get(nodeKey);
    lastIndex = nextIndex;
         else { //no more "/" , it means we are at end of s, and that all parent nodes for this leaf-node exist.
         // and we just add the leaf node to last node
         String leafName = s.substring(lastIndex, s.length());
         DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode(leafName);
         lastNode.add(leafNode);
         break; // go to next s
         //You first make your tree structure with DefaultMutableNodes,
         //Then make a DefaultTreeModel with the root node,
         //Then make a Tree with the DefaultTreeModel
         DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree yourTree = new JTree(treeModel);
    getContentPane().add(yourTree, BorderLayout.CENTER);
    show();
    public static void main(String[] args) {
         new TreeStrings();
    Anything else?

Maybe you are looking for

  • Can't import songs from iTunes to my iPod

    I'm not sure if I have a problem with iTunes or my iPod, but I'll try this forum anyway. I already asked this under the iTunes category. Basically, there's a sudden problem where, for the life of me, my iPod will not accept new music. It shows up fin

  • New View Columns are Blank on Rendered JSF Page

    In an existing application, I am trying to add a few columns to an ADF Read-Only Table on an existing jsf page. In the model project, I added the columns to the read-only view object by changing the SQL statement. I then tested the business layer cha

  • Determine the number of days in a False period in a Temporal Boolean

    Hi all, I need to determiine the number of days based on a condition that lies on the gaps between the periods. My input consists of multiple periods. The length of the gap is the condition to determine the start date for summation. However, there ca

  • C# code stored in Oracle

    Has anyone heard of the following? http://www.oracle.com/goto/newsletters/netdev/0409/idc_interop-pdf.html?msgid=7590204 An interesting capability first introduced in Oracle Database 10g is the ability to run .NET code as Oracle stored procedures. It

  • Can someBody HELP me, I came from T-SQL

    I got to made some function but doesn't work. I mean is VALID, but I don't get the result that I want. I came from T-SQL developer. I need to make a function that return a value, something like this. Function Duall ( var in varchar2) Return varchar2