Positioning expanded nodes on JTree

Hey all,
Does anyone know how to position an expanded node on a JTree to scroll inwards to the right (towards the current expanded level) and move to the top of the Panel it sits in? Kinda like Windows explorer.
Any help will be greatly appreciated. Thanks in advance,
zia

Try to use
setScrollsOnExpand(boolean�newValue) method of JTree
regards
Stas

Similar Messages

  • Expanding nodes in JTree

    I have an application that uses JTree
    I create the Jtree but I want to expand to see and select a node.
    I have the object of the node and the TreePath but I can't expand the tree using expandPath(), makeVisible(), scrollPathToVisible(path), etc. It seems that JTree doesn't detect the path I use as input.
    But when I use setSelectionPath(path) it is selected (I know because I see information about the node) but it is not displayed nor viewable.
    I only can expand nodes using expandRow(int).
    Does anybody know how expand and select nodes without clicking with mouse?

    expandPath(Treepath treePath) should work. Its possible that your treePath is wrong. How do you get the treePath?

  • Select Expanded nodes in JTree

    Hi all,
    In the given tree structure, I want to get a node to be selected, once it is expanded.
    + Folder1
    - Folder2
          |
          |__-Folder3
           |
           |__-Folder4
              |
                |__ file1.docCurrently, if I have Folder1 selected and if I expand Folder2, the selection remains at
    Folder1 itself. I need to change the selection to Folder2.
    Also, I need to get the path of the expanded node . ie; when Folder4 is expanded, I need to
    get Folder4 selected and path has to be obtained as \Folder2\Folder3\Folder4.
    I found this link helpful-- http://forums.sun.com/thread.jspa?messageID=3616726, but there
    also, the path is obtained based on selection and not based on expansion.
    Please help with a solution
    Regards,
    Anees

    AneesAhamed wrote:
    Hi all,
    In the given tree structure, I want to get a node to be selected, once it is expanded.
    + Folder1
    - Folder2
    |
    |__-Folder3
           |
           |__-Folder4
              |
                |__ file1.docCurrently, if I have Folder1 selected and if I expand Folder2, the selection remains at
    Folder1 itself. I need to change the selection to Folder2.
    Also, I need to get the path of the expanded node . ie; when Folder4 is expanded, I need to
    get Folder4 selected and path has to be obtained as \Folder2\Folder3\Folder4.
    I found this link helpful-- http://forums.sun.com/thread.jspa?messageID=3616726, but there
    also, the path is obtained based on selection and not based on expansion.
    Please help with a solution
    Regards,
    AneesTo expand any node you need to "know" it either due to a user's mouse click or inside the code that expands it directly, something like :
    - by mouse click :
    myJTree.addMouseListener(new MouseAdapter()
         public void mouseClicked(MouseEvent e)
              TreePath treePath = getPathForLocation(e.getX(), e.getY());
    });- direct code :
    public void treeWillExpand(TreeExpansionEvent e)
         TreePath treePath = e.getPath();
    }Then you can get the corresponding node from the TreePath :
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();But for a selection this should be enough :
    myJTree.setSelectionPath(treePath);
    myJTree.scrollPathToVisible(treePath);Regards,
    Lara.

  • Trouble with JTree's and autmoatically expanding nodes

    I am writing an application which uses a JTree as a method of browsing through a certain structure (like a file system). I am having a little trouble though, with a number of small issues, which I am finding hard to get answers through searches (and have spent a fair while searching). In navigating the tree, I want to be able to automatically expand nodes.
    Firstly, I want the Root node to automatically be expanded. I cannot see ways of doing this. I have seen references to EXPANDED being set for the JTree constructor, but I cannot see any reference in the 1.6 API for this.
    Secondly, I want to be able to expand or hide the contents of nodes through other means than clicking on the icon to the left of a non-leaf-node. For example a button that would hide the contents of (i.e. close) the currently selected node. Code such as:
    myNode.setExpanded(true);
    myNode.setExpanded(false);and
    myNode.isExpanded();

    That's the ticket - again something I had seen, but had been using in the wrong way, but your suggestion has helped me get it right. I was trying to expand the path before any more nodes were added to the root node. Then nodes are added, and the application loaded with the root node collapsed. So now I have placed the call at the end of the recursive call to populate the tree.
    Thanks again.

  • Expanded node and children are seen only after second expansion

    Hi,
    I am using a simple JTree control. I am populating children of nodes dynamically when the node is expanded. For this, I first add a "dummy" item for each node under the root, so that the "+" sign appears next to the node. When a node is expanded, I delete the "dummy" node and add children to it. However, the first time I expand the node, the node actually doesn't expand, though treeExpanded() gets called and all children are added correctly (I verified by debugging). When I expand the tree the second time, I can see the expanded node.
    I am using TreeModel's removeNodeFromParent(childNode) and insertNodeInto(childNode, parentNode, childIndex) method to remove and add children respectively.I believe we don't have to explicitly call TreeModel's nodeChanged(), nodesWereInserted() etc?
    Could you please let me know if I am missing something fundamental here?
    Thanks in advance,
    Praneeth

    Hi db,
    I didn't realize that there was a response to my earlier thread. I added the thread to my watchlist. I was under the impression that I would be notified via email in case of a reply to the thread. However, I didn't receive any. Anyway, I did reply to that response there now.

  • Help needed with finding node in JTree

    Hi,
    In my application i will be entering some string data in a text box for search criteria.
    When I click on search, I will get data from database which will be shown as a JTree.
    This Jtree will have some nodes in which, node with string entered in the search text box exists.
    I need to focus on this node and I have only a string to find this node.
    How can I do this?How can I find a node in JTree using string value?
    Is there any alternate option by which I can achive my need?
    Please suggest.
    Thanks.

    @OP: please assign your dukes.
    @Andre_Uhres: if you don't get rewarded in the next couple of days, please let me know here to get at least one duke for your effort.
    Bye.

  • Problem inserting new node into JTree with depthFirstEnumeration()

    Hello,
    I'm currently trying to use depthFirstEnumeration() to add and delete nodes for a simple JTree. I've written a method to handle this, but it keeps coming back with an exception saying that 'new child is an ancestor'.
    All I'm trying to do is add and delete nodes from a JTree using add and remove buttons within a swing program. When a user adds the new node the JTree needs to be updated with new labels in sequential order dependent upon a depthFirst traversal of the JTree.
    My current code for the add button is as follows,
    public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            Enumeration e = rootNode.depthFirstEnumeration();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    while (e.hasMoreElements()) {
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)e.nextElement();
                     // treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    //System.out.print(newNode.getUserObject() + "" + newNodeSuffix++);
                    String label = "Node"+i;
                    treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    i++;
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);
                    //System.out.println();
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        } As you can see in the above code, I've tested the incrementing of the new nodes in a System.out.print() statement and they appear to be incrementing correctly. I just can't see how to correctly output the labels for the nodes.
    Any help and advice always appreciated.

    This is about the 5th posting on the same question. Here is the link to the last posting so you can see what has already been suggested so you don't waste your time making the same suggestion.
    http://forum.java.sun.com/thread.jspa?threadID=704980
    The OP doesn't seem to understand that nodes don't just rename themselves and that renderers will only display the text of the current node. If you want the text displayed to changed, then you need to change the text associated with each node, which means iterating through the entire tree to update each node with new text. Then again, maybe I don't understand the question, but the OP keeps posting the same question without any additional information.

  • Drag and Drop nodes in JTree

    Is there a way to drap and drop JTree nodes without resorting to hacks? http://www.javaworld.com/javatips/jw-javatip97.html outlines a hack to get drag and drop working but it is kinda old. I am wondering whether there is a now a way to do this in Swing. http://weblogs.java.net/blog/shan_man/archive/2006/01/first_class_dra.html outlines a seemingly promising way but when I tried it it still wouldn't let me drag JTree nodes. (btw, if you are going to try it, you must replace TransferHandler.TransferInfo with TransferHandler.TransferSupport. It has apprently been renamed.)

    I have implemented drag and drop of nodes in JTree they same way it is explained in JavaWorld link that you mentioned, I customized it for my application and it worked great.

  • Help in getting current expanded node in Tree UI

    HI,
    I have a requirement to build a tree dynamically. On expanding each node I need to create sub nodes inside that. But it is always creating inside the node where the lead selection is and not inside the current expanded node. Even though I have used getTreeSelection () to get the current element.
    <b>Detailed description about the application.,</b>
    I have created a context with the following structure,
    TreeNode (0..n)
    |
    |--> ChildNode (recursive SiteTree)
    |--> Name (string)
    I have created a Tree UI Element in the view and inserted a node type 'TreeNodeType'.
    I have set the properties of the inserted node type as given bellow,
    Value Attribute in TreeNode -> Name I have assigned to 'Text' property of 'TreeNodeType'.
    Initially I have created four nodes in the init() method ., using the following code :
    for(int i=0;i<3;i++)
    IPrivateTestTreeView.ITreeNodeNode treenode=wdContext.nodeTreeNode();
    IPrivateTestTreeView.ITreeNodeElement treeelement=wdContext.createTreeNodeElement();
    treeelement.setName("Testroot:"+i);
    treenode.addElement(treeelement);
    Now I need to create sub-nodes for this dynamically.,
    I have created an action and called it in 'onLoadChildren' event of 'TreeNodeType' with the following code:
    public void OnCurrentSelection()
    IPrivateTestTreeView.ITreeNodeElement el = wdContext.nodeTreeNode().getTreeSelection();
    wdComponentAPI.getMessageManager().reportSuccess(el.getName());
    <b>
    Where this returns me only the name of LeadSelection node and not the  node which i try to expand.  </b>
    Is there anyway I can get the currently expanded node., Kindly help me out in this.
    Points will be rewarded for helpful answers. Thanks in advance.
    Regards,
    Nirmal

    HI Ayyapparaj ,
    <b>First I would like to thank you for your reply.</b>
    So it means that we cannot identify the currently expanded node in tree UI element and It will always be the lead selection node we will be able to get rite?
    Can we make the current lead selection to currently expanded node 'By Default'?
    Coming back to your solution.,
    I created a context element 'isExpanded' of type boolean inside the TreeNode.
    You said that there will be a call made to 'getter and setter' methods while we expand the node and we can set the lead selection to that element from there.
    Could you please give me some more details of how to achieve it.
    Thanks in advance.
    Regards,
    Nirmal G

  • Af:treeTable component: API to return list of expanded nodes?

    Hi,
    In my UI design, I am using a tree table (af:treeTable component). Does the framework support API to return (at any given time) a list of all expanded nodes?
    I realize that I can build logic to 1. return the currently selected node, then 2. query up all of the child nodes of this selected node. However, I'm wondering if, say at a particular instant, multiple nodes have been expanded, and I need a list of all of these nodes for every level in the tree table?
    Thanks in advance,
    Monica

    Hi John,
    I am using 11g. From the javadoc, I see that getDisclosedRowKeys() returns "set of disclosed rows for [tree-table] component" and "each entry in the set is a rowKey."
    What exactly is the definition of a "disclosed row"? I'm guessing this means any & all rows shown from UI, which would return all rows (including parent nodes of newly expanded nodes)?
    Is there a way to return all child nodes (newly displayed rows) of expanded nodes? To clarify, I'm trying to gather rows level by level. If a node has been expanded at level n, I would like to get a new list of nodes at level (n+1).
    Thanks,
    Monica

  • Wordwrap nodes in jtree

    Anyone know how we can do wordwrap of nodes in jtree?
    Please help...
    Thanks.

    Any example on this? what html code should I use? The simplest possible, eg
    yourNode.setText("<html>" + yourNodeText + "</html>");Most JComponents can render this html string and produce a good result. But if you wanna get a little more complex and use styles and other web things, then do as said, (two posts above) and use a JEditorPane specifically for cell renderer
    ICE

  • How to set the default tree node in JTree?

    I want to set a default tree node in JTree when start the program,
    what is the method or the function to call?
    Thanks~

    If you by "default" mean "selected", then you can use one of the setSelectionXXX methods in the JTree API.
    If you by "default" mean something else, never mind this post :-)

  • Setting custom color for selected node in JTree?

    Hi,
    i want to set my own color for selected node in JTree. i don't want to set for all the nodes...how to set Color for Selected node using TreeCellRender class?
    Thanks
    Mani

    I assume you are not setting a custom tree cell renderer...
    javax.swing.JTree theTree = ...;
    java.awt.Color newBGColor = ...;
    ((javax.swing.tree.DefaultTreeCellRenderer)theTree.getCellRenderer())
        .setBackgroundSelectionColor(newColor);

  • Only 1 expanded node each time - MenuTree

    I use a <af:menuTree> component with 2 level nodes.
    How can I put only one expanded node each time (of first level). By other words, when I expand 1 node (first level) the others expanded nodes must not be expanded automatically ?
    Thanks,
    Sérgio Morais

    Sergio,
    managed bean:
    package adf.test;
    import java.util.Set;
    import oracle.adf.view.faces.component.core.nav.CoreMenuTree;
    import oracle.adf.view.faces.event.DisclosureEvent;
    import oracle.adf.view.faces.model.PathSet;
    public class MenuTreeBean {
    public MenuTreeBean() {
    public void onDisclosure(DisclosureEvent disclosureEvent) {
    CoreMenuTree cmt = (CoreMenuTree) disclosureEvent.getSource();
    Object rwKey = cmt.getRowKey();
    //quick and dirty check for tree level
    if (rwKey.toString().indexOf(",") == -1){
    PathSet ps = cmt.getTreeState();
    Set ks = ps.getKeySet();
    ks.clear();
    ks.add(rwKey);
    JSF tree
    <af:menuBar id="mbar">
    <af:menuTree value="#{bindings.DepartmentsView1.treeModel}" var="node"
    disclosureListener="#{menuTreeBean.onDisclosure}"
    id="menutree">
    <f:facet name="nodeStamp">
    <af:outputText value="#{node}" id="nodeId"/>
    </f:facet>
    </af:menuTree>
    </af:menuBar>
    Frank

  • Add node to JTree

    I have an already populated JTree. At Runtime I add one or more node to JTree, using something like
    parentNode.add(newNode)....
    If I call a repaint method, the new node isn't visible, I have to reload model using
    DefaultTreeModel dtm = ((DefaultTreeModel)myTree.getModel());
    TreeNode rootNode = (TreeNode) dtm.getRoot();
    dtm.reload(rootNode);
    Unfortunately this method cause the lost of focus on the currently selected node and the collapse of all JTree around its root node; If I change an existing node (for example changing its text or icon) I must reload the model too!!!
    Does exist an other more "soft" method to change the aspect of a JTree without reload the entire model?

    You must use or implement the
        public void valueForPathChanged(javax.swing.tree.TreePath path,java.lang.Object newNode) {
            Object[]    p = path.getPath();
            Object[]    pp = p;
            //insert node here
            int[] ci = new int[] {index};
            Object[] cc = new Object[] {node};
            fireTreeNodesChanged(this, pp, ci, cc);
            fireTreeStructureChanged(this, pp, ci, cc);
        }from the TreeModel. To fire the last two is essensial.
    I implemented a GP in JAVA so i had the same problem wehn i started.

Maybe you are looking for