Navigating to a Selected node in a JTree

Hi
I have a Jtree which has nodes and sub nodes.Whenever I expand a node and click on its subnode I want to highlight/navigate to that subnode in the tree.
e.g:
Root
--- node1
--node2
--node3
--- node2
--node4
When I expand node1 and click on node2 I want the other node2 highlighted.
I tried the following thing but it does not work:
public void valueChanged(TreeSelectionEvent e) {
Object[] obj = new Object[2];
obj[0] = (DefaultMutableTreeNode)node.getPath()[0].getChildAt(0);
obj[1] = (DefaultMutableTreeNode)node.getPath()[0].getChildAt(1);
TreePath tp=new TreePath(obj);
tree.setSelectionPath(tp);
Any suggestions??

thanks a lot for all your inputs.I was able to solve the problem using the following code:
DefaultTreeModel dt = (DefaultTreeModel )tree.getModel();
TreeNode[] nodes = dt.getPathToRoot(childNode);
TreePath path = new TreePath(nodes);
tree.scrollPathToVisible(path);
tree.setSelectionPath(path);
One of the things which I was doing incorrectly was creating the array of nodes to be passed to the treepath constructor manulaly.When I replaced it with the getPathToRoot method of the model it worked!!..
Thanks a lot once again!!

Similar Messages

  • How could i get the selected node in the JTree

    getLastSelectedPathComponent() �returns the parent node of currenr selected, so how could I get the selected node itself in the JTree
    I will appretiate for any help!

    i think you can get by....
    TreePath treePath = tree.getSelectionPath();
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) treePath.getLastPathComponent();

  • How to get  a Current Navigation model  Current Selection (node) ID

    Hi,
    we are using default navigation model for page navigation in our application.
    I am trying to get Id of Default Navigation model node, I am able to get the Title using following code which available in globe template.
    Code – pageTemaplate_globe.jspx :
    <af:forEach var="node" varStatus="vs"
    items="#{navigationContext.defaultNavigationModel.listModel['startNode=/, includeStartNode=false']}">
    <af:subform id="pt_sfm1">
    <div class="bea-portal-book-primary-menu-single-item">
    <af:switcher id="pt_sw1"
    facetName="#{(empty node.attributes['Target']) || (node.attributes['Target'] == '_popup') ? 'command' : 'golink'}">
    <f:facet name="command">
    <af:commandLink id="pt_cl1" text="#{node.title}"
    action="#{MyAccBean.menuItemListAction}"
    disabled="#{not node.navigable}"
    actionListener="#{navigationContext.processAction}"
    clientComponent="#{node.attributes['Target'] == '_popup' ? true : false}">
    <!-- pass node to processAction for setting current selection and navigation -->
    <f:attribute name="node" value="#{node}"/>
    <af:setActionListener from="#{node.title}"
    to="#{pageFlowScope.menunodetitle}"/>
    I am using +<af:setActionListener/>+ to set Title to variable and using in that in code.
    Is there a way that i can get ID in the same way as title?
    I see following EL from documentation but there is no ID attributes available.
    EL: #{navigationContext.defaultNavigationModel.currentSelection.attributes['Description']}
    EL: #{navigationContext.defaultNavigationModel.currentSelection.title}
    Please help me…
    Thank you,
    SP

    Hi.
    Doesn't exist direct access to node Id but you can use this EL Expression to get it:
    #{node.prettyUrlPath[node.depth]}Regards.

  • Coloring selected nodes in JTree

    i am currently using setCellRenderer() for highlighting a selected node in my JTree.but when i select another node, the previously selected node loses its highlight.i would like to know of how i could make the highlight in the selected nodes remain persistent.

    I am currently using DISCONTIGUOUS_TREE_SELECTION only. my requirement is that i should be able to select any number of nodes.so i use this selection.
    but at the same time, my highlight in selected nodes should be like a toggle-state.
    if i select an already selected node ( say A), the highlight has to go away.
    and at the same time, th highlight on previously selected nodes (say B, C) should be persistent.
    am currently using TreeSelectionListener. and for rendering am using SetCellRenderer.
    in this scenario, how could my work be accomplished?

  • Change icon of a non selected node in JTree

    Hello
    I have a swing application contening a JTree.
    I'd like to know how to change the icon of a non selected node in my tree. I have the information about the node and its path. I try to change userObject information and the icon of the node with the setIcon of (DefaultMutableTreeNode), and reload the node (DefaultTreeModel) but it doesn't work.
    Do I have to set the change in my CellRenderer ?
    Any advice will be welcome
    Anne

    If you carefully look at the java tutorial tree, the change is made for all the leaf icon. What I want is to change the icon of a not selected node of my tree while I do other stuff with the other nodes like select, display their contents, drag them ...
    the operation of a not selected node is independant from the selection in the tree.
    So I still ask how to force a node to reload and take care of the change of his icon.
    Anne

  • JTree: How to get the currently selected node

    How do I get the currently selected node in JTree?
    getLastSelectedPathComponent() this method always return the last selected node and not the current one.
    Thanks in advance
    Sachin

    Use
    TreePath selectedPath = tree.getSelectionPath()If your tree allows multiple selections, use
    TreePath [] selectedPaths = tree.getSelectionPaths() this will return an array of all selected tree paths.
    Once you get the tree path, call the treePath.getLastPathComponent(). this should tell you the currently selected node.
    Hope this helps
    Sai Pullabhotla

  • Don't want nodes in a JTree to be selectable

    I have a JTree and don't want the user to be allowed to select nodes, just leafs should be selectable. Any ideas?
    Thanks,
    pi-j

    Subclass DefaultTreeSelectionModel and override any methods which add new selection paths to prevent nodes from being added to the tree selection paths.

  • Selectively editing nodes in a JTree

    I need to make certain nodes in a JTree editable, without making every node in the tree editable. How can I accomplish this?

    Is there some kind of method in a JTree or a DefaultMutableTreeNode that I can call to select the node's text and be able to change it?Hmm. And you did read the API for JTree looking for such methods before you posted here, didn't you?
    So tell us which methods you found to be likely candidates.
    db

  • How to allow multiple selection of nodes in a JTree

    How to allow multiple selection of nodes in a JTree ?
    Thanks
    S.Satish

    By default when you create new instance og JTree the selection model is multiple selection. And if you want to change it you use next:
    tee.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    Hope will help!

  • JTree and selected node question

    Hello
    Is it possible to convert the selected node to an int?
    I guess I'm looking for something llike this.
    int nodeNumber = node.getSelectedIndex();
    There is nothing like that in the API, and it would help greatly if I could find a way do this.
    Thanks
    Have a good holiday
    Jim

    From the API for JTree
    public int getMinSelectionRow()
    Gets the first selected row.
    Returns:
    an integer designating the first selected row, where 0 is the first row in the display
    But I think this is based on how many rows are displayed at the present time and might change if the tree is opened above it.

  • How to select node in JTree without firing event?

    I have got standard situation. JTree in the left panel, and several edit boxes in right panel. Certainly, I have TreeSelectionListener, which on every tree node selection shows corresponding model values in edit boxes.
    I'd like to implement next logic:
    1. Something was changed in any edit box in right panel. Model has been changed.
    2. User clicks on different node in tree.
    3. Dialog "Message was not saved. Save?" with Yes/No/Cancel buttons are shown.
    Yes/No buttons are easy to handle.
    Question is about Cancel. I'd like on Cancel button left all edit boxes in their present state (do not restore values from saved model) and select back node, which wasn't saved.
    Problem is next. If I select node by setSelectionPath or smth like that, but... JTree fires event and my listener receives onTreeItemSelected back, which checks that node wasn't saved and ......
    Who does have any idea, or have done similar tasks? How can I select node and do not allow tree fire event this time?
    Thanks in advance.

    First, as soon as the model changes (when editing any
    combo box) some flag will be set. Now the logic which
    updates the combo boxes will do it only on a change of
    the current node and (this is new) if the flag wasn't
    set. You should have some flag anyway because somehow
    you must determine when to show the dialog, shouldn't
    you?Yes, I have got this logic implemented. But it's only the half :)
    I know exactly when my model has been changed, but if it was changed, i'd like to ask user what to do next - svae/loose changes/cancel
    And on cancel i'd like to select last edited tree node and do not get event from tree at that moment.
    >
    Second way, prevent selecting a new node if that flag
    has been set. You could do this by subclassing
    DefaultTreeSelectionModel and overriding some methods
    (setSelectionPath() et al).Ok. I'll investigate this.
    >
    MichaelThanks.

  • JTree get selected node/object values

    I wan to get all the selected nodes/objects values that I added to the JTree. How can I do this?
    Thanks.

    TreePath[] paths = tree.getSelectedPath();
    for(int i = 0; i < paths.length; i++){
    TreeNode node = (TreeNode)paths.getLastPathComponent();
    Object mySelectedObject = node.getUserObject();
    }Some minor Errors
    We have to use array paths[i] instead of paths
    The correct code as used by me is
            javax.swing.tree.TreePath[] paths = jTree1.getSelectionModel().getSelectionPaths();
            for(int i = 0; i < paths.length; i++){
                javax.swing.tree.TreeNode node = (javax.swing.tree.TreeNode)paths.getLastPathComponent();
    System.out.println(((javax.swing.tree.DefaultMutableTreeNode)node).getUserObject());
    CSJakharia

  • How to select a node in a JTree by name

    I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help
    Thanks!

    I have a JTree and each node on the JTree has a string name. I also have a JEditorPane that lists all these names at start up. If the user clicks on one of these names, I want to catch the HyperlinkEvent and automatically select that node in the JTree.
    So in short, I have the String name of the node that I want to programatically select.
    Thanks!

  • 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);

  • Selecting a node in a JTree knowing his path

    Hello for all,
    I'm trying to select a specific node in a JTree component by clicking a button.. this is my code :
    private DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("root");
    private DefaultTreeModel treeModel = new DefaultTreeModel(treeNode);
    private JTree tree = new JTree(treeModel);
    private JButton button = new JButton("Select");
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("child1");
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("child2");
    child1.add(new DefaultMutableTreeNode("child11"));
    treeNode.add(child1);
    treeNode.add(child2);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        TreePath path = new TreePath(new Object[]{"root", "child1"});               
        tree.setExpandsSelectedPaths(true);
        tree.scrollPathToVisible(path);
    });as you can see, I want to select the node with the path "root/child1"..
    but I'm getting this exception : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.tree.TreeNode..
    any ideas ?

    You will want to read the second sentence in the TreePath comments section.
    Also, read the second sentence in the TreePath Method Detail section for the
    getLastPathComponent method.
    With these clues &#8212; try getting a TreePath from the tree you are working with.
    For example, you can try something like tree.getPathForRow(row) using the
    visible row index of "child1". Since the TreePath returned comes from the tree
    it will understand what to do with it. You can check the class name of the
    components that are returned in the TreePath to confirm this. And it will
    explain the exception you quoted.

Maybe you are looking for

  • Can I convert an iPhoto hardback book to a paperback book for a new order?

    I've just ordered a hardback book through iPhoto. I'd like to now order a paperback version of the same book but can't work out how to do this. I can duplicate my book, but I can't find a way of changing it to paperback. Is this possible?

  • Taking long time to READ records

    Hi, I am fetching Purchase order numbers and vendors from EKKO and LFA1 table join and comapring them with plant entries from EKPO table based on REGIO field. then based on those values of EBELN and LIFNR wherein REGIO field doesnt match, m trying to

  • How to Publish old iweb blog saved in pages?

    I have a series of blogs created in an early version of iweb. I saved them to my desktop in a folder in a Pages format. If I want to export them to iweb 09 to eventually publish them to machighway (since mobileme is "dying").  There are two choices f

  • QSIG Forward Issue

    Hi, I've got problem betwen CUCM and a node of cluster of Alcatel PABX. On each site, i've got an ISR with QSIG link to local Alcatel PABX. All the Alcatel PABX is on the same cluster. When a Cisco User want to call an Alcatel User, he take the local

  • Webservice Endpoint URL

    Hello, I have developed a Webservice Client in Netbeans 5.5 It al works perfect, but how do i change the URL for the ENDpoint or the URL from the webservice? Greetings