JTree leaf selection

hi guys,
I am developing a jTree for a networking product,which will show all the network elements present in the network.The tree also shows the device status like Up,Down etc.I have provided a button to refresh the jtree to update the status of the devices.But after updating the jtree when i try to expand or setSelected path to previously selected leaf,the jTree is expanding only till the parent of the leaf.Here is the code which i have written:
public void addRootNodes()
          TreePath path=jTree.getSelectionPath();
          DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
          TopologyUtilities.getNetworkCollectionDetails();
          TopologyUtilities.getRuntimeDataMapOnRefresh();
          initializeData();
          rootBusiness.removeAllChildren();
          rootNetwork.removeAllChildren();
          rootDiscovery.removeAllChildren();
          addRegionLocationToBusinessView();
          AddNodesToTree.addRoutersToNetworkView(configuredNetworkCollection, dataMap, rootNetwork);
          AddNodesToTree.addRoutersToDiscoveryView(discoveredNetworkCollection, configuredNetworkCollection, dataMap, rootDiscovery);
          treeModel.reload();
          panel.removeAll();
          jTree.setSelectionPath(path);
Thanks for the help in advance
bye,
Srinivas

Since you have a reference to a DefaultMutableTreeNode object, can't you do something like
TreeNode[] nodes = n.getPath();
TreePath path = new TreePath(nodes);
tree.setSelectionPath(path);

Similar Messages

  • Jtree leaf selection on jinternal frame

    Hi all,
    I m using a splitpane ...on left hand side i m using a tree and right side i m using a desktoppane where i'll open the internal frames...my tree leaf and internalframe title is same ...
    my question is when when i select any internalframe it should select corresponding leaf(becoz my leaf and t\internalframe is same)...and same i wanna do for tree when i click in any leaf ...internal frame should actived and come to front...
    pls can anyone tell me how to proceed for this...
    can anyone provide me any examples ....pls help me out
    regards
    Tarique

    Since you have a reference to a DefaultMutableTreeNode object, can't you do something like
    TreeNode[] nodes = n.getPath();
    TreePath path = new TreePath(nodes);
    tree.setSelectionPath(path);

  • Right mouse button click in a JTree leaf

    Hi,
    how can I add a mouse listener in a JTree leaf? I have DOM nodes wrapped and a JTree model adapter to set up the JTree. I want the popup menu to show everytime the user clicks on a leaf, but not on the tree itself.
    Thanks!

    Really you just have to add your listener to the tree itself, then use the Point to find the corresponding TreePath (getPathForLocation), from which you'll easily find the node.

  • JTree Nimbus selection treeNode

    I made a jtree with a custom TreeCellRenderer. The leaf nodes are a jpanel with a checkbox in and JPanel. The problem now is that when you select a tree node, there is a selection color box beside the jpanel.
    Here is a sscce:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class Users {
        private static JFrame frame;
        private static JPanel usersPanel;
        private JTree usersTree;
        public Users(){
            usersPanel = new JPanel();
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Gebruikers");
            DefaultMutableTreeNode willie = new DefaultMutableTreeNode("Willie");
            DefaultMutableTreeNode Anna = new DefaultMutableTreeNode("Anna");
            rootNode.add(willie);
            rootNode.add(Anna);
            usersTree = new JTree(rootNode);
            myTreeWithCheckBoxRenderer renderer = new myTreeWithCheckBoxRenderer();
            usersTree.setCellRenderer(renderer);
            usersTree.setRootVisible(true);
            usersTree.setEditable(false);
            usersTree.setOpaque(false);
            usersPanel.add(usersTree);
        class myTreeWithCheckBoxRenderer extends DefaultTreeCellRenderer {
            DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
            JPanel panel;
            JCheckBox checkBox;
            JLabel label;
            public myTreeWithCheckBoxRenderer() {
                checkBox = new JCheckBox();
                label = new JLabel("Gebruikers");
                panel = new JPanel(new BorderLayout());
                panel.add(checkBox, BorderLayout.WEST);
                panel.add(label, BorderLayout.EAST);
                panel.setBackground(Color.red);
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                Component returnValue;
                if(!leaf){
                    renderer.setBackgroundSelectionColor(null);
                    renderer.setText("Gebruikers");
                    returnValue = renderer;
                else{
                    if(hasFocus){
                        panel.setBackground(Color.blue);
                    returnValue = panel;
                return returnValue;
        private static void createAndShowGUI(){
            new Users();
            frame = new JFrame("Tree");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(usersPanel);
            frame.pack();
            frame.setPreferredSize(new Dimension(800, 600));
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
         public static void main (String[] args){
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
            } catch (UnsupportedLookAndFeelException e) {
                // handle exception
            } catch (ClassNotFoundException e) {
                // handle exception
            } catch (InstantiationException e) {
                // handle exception
            } catch (IllegalAccessException e) {
                // handle exception
            javax.swing.SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                    createAndShowGUI();
    }I tried using a DefaultTreeCellRenderer and use the setBackgroundSelectionColor() method to null, but it doesn't change anything. Also setting the background of the JPanel to null doesn't make a change when you check with (if(hasFocus)). However I have the impression that nimbus is causing the problem, because if you comment the nimbus part out, you don't have the selection box anymore.
    Does anyone has an idea to solve this?
    Edited by: Kligham on 30-aug-2010 19:25

    Kligham wrote:
    Thank you very much!You're welcome.
    Kligham wrote:
    Problem solved. So since this cell background rendering is a Nimbus "feature", can I assume that the "not displaying of angled lines" also is a Nimbus "feature". Since the JTree tutorial says this should do the trick:
    usersTree.putClientProperty("JTree.lineStyle", "Angled");So I probably have to override it the same way, so I was wondering how you know what UIDefaults there are?Well, "JTree.lineStyle" is actually a client property and not a UIDefaults property. In other words, "JTree.lineStyle" is on the same logical level as "Nimbus.Overrides". Unfortunately, there is no way to determine which client properties a component or a component UI implementation supports except carefully examining its source code. javax.swing.plaf.synth.SynthTreeUI (the Nimbus TreeUI implementation) doesn't seem to support any client properties. It might be handled somewhere else, though.
    As an alternative to using "JTree.lineStyle", you could try to use a backgroundPainter that draws angle lines instead of the "do nothing" painter I suggested.
    To determine which UIDefaults properties are available for a given LaF implementation, you can iterate over the UIDefaults' entrySet (UIDefaults is a subclass of Hashtable). For Nimbus specifically, Jasper Potts already did that. See the [corresponding blog entry|http://www.jasperpotts.com/blog/2008/08/nimbus-uimanager-uidefaults/] and [Nimbus UIDefaults Properties List|http://jasperpotts.com/blogfiles/nimbusdefaults/nimbus.html]

  • Jtree leaf custom icons

    I created my own class that extands DefaultTreeCellRenderer and overrided the function getTreeCellRendererComponent.For now I see the customed icon on the leaf,but when I touch with the mouse the panel the vision of the leaf comes back to default.I tried to do repaint it's doesn't help me
    May be you have any suggestions?

    ok I did the following code in a previous project to handle a similer requirement
    It s from a large project so I'll only post a small part and hope that you can understand it
    If you dont just let me know which part
    package lrmk.client.nav;
    import lrmk.client.*;
    import lrmk.client.wnd.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import javax.swing.*;
    public class NavCellRenderer implements javax.swing.tree.TreeCellRenderer
       DefaultTreeCellRenderer form_window  =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer dialog_box   =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer table_window =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer custom =  new DefaultTreeCellRenderer();
       DefaultTreeCellRenderer def  =  new DefaultTreeCellRenderer();
       public NavCellRenderer(){
          form_window.setLeafIcon(ClientGlobals.getImageIcon("lrmk/client/images/form_icon.gif"));
          dialog_box.setLeafIcon(ClientGlobals.getImageIcon("lrmk/client/images/dialog_icon.gif"));
          table_window.setLeafIcon(ClientGlobals.getImageIcon("lrmk/client/images/table_icon.gif"));
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          TreeCellRenderer r = def;
          NavNode nn = null;
          if (value instanceof NavNode)
             nn = (NavNode)value;
          if (nn != null && nn.getIcon() != null)
             r = custom;
             custom.setLeafIcon(nn.getIcon());
          else if (value instanceof WindowNavNode)
             WindowNavNode wnn = (WindowNavNode)value;
             if (CDialogBox.class.isAssignableFrom(wnn.getWndClass()))
                r = dialog_box;
             else
                String name = wnn.getWndClass().getName();
                name = name.substring(name.lastIndexOf("."));
                if (name.startsWith(".Frm"))
                   r = form_window;
                else if (name.startsWith(".Tbw"))
                   r = table_window;
          return r.getTreeCellRendererComponent(tree,value,selected,expanded,leaf,row,hasFocus);
    }

  • JTree and selected tree node

    I am allowing the user to search for a node in a JTree. I can find the node and progamatically expand and select the node. What I would like to do next is find the x,y coordinates of this selected node so I can use Robot to move the mouse to this node. I have hover help which is chock full of information in HTML describing this node, however, the user now is required to move the cursor to this selected node to see the hover help.
    Any help would be appreciated.

    Hi ,
    try this
    jlabel.setIcon( null ) ;

  • Jtree custom selection

    I use the jTree. When an element is selected - i dont like how it looks.
    Check the screenshot : there are two selected areas - a standart one (top) and a custom one(bottom), dont pay attention to the gradient.
    The designer made an improved variant. As you can see, the selection exceeds the jTree and goes over the JPanel, which comprises the jTree.
    How can I make it like this in my app?
    P.S.
    I have an idea to make a half-transparent JPanel and place it over the tree... but I am not sure about the TRUE-ness of this solution :)

    I use the jTree. When an element is selected - i dont like how it looks.
    Check the screenshot : there are two selected areas - a standart one (top) and a custom one(bottom), dont pay attention to the gradient.
    The designer made an improved variant. As you can see, the selection exceeds the jTree and goes over the JPanel, which comprises the jTree.
    How can I make it like this in my app?
    P.S.
    I have an idea to make a half-transparent JPanel and place it over the tree... but I am not sure about the TRUE-ness of this solution :)

  • 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.

  • JTree - multiple selection doesn't highlight tree nodes

    I have a JTree which was working great with single selection of objects within it. Now i'm expanding this to work with multiple selected objects at the same time, but the objects are not visibly highlighted in the tree.
    I switched to using DISCONTIGUOUS_TREE_SELECTION, and using setSelectionPaths(TreePath[]) instead of setSelectionPath(TreePath). This works fine, except that the newly selected paths don't visually highlight any more (worked fine with single selection).
    I had thought that the RowMapper was the culprit, but the default VariableHeightLayoutCache seems to be in place and ok. What should i be checking to get this to work right?
    Thanks.

    /me beats forehead against the desk..
    TreePath selectionPath = new TreePath( entityNode.getPath() );
    NOT just
    TreePath selectionPath = new TreePath( entityNode );

  • JTree path selection

    I have a JTree on the left scrollpane and on clicking the value of a node, I display the value in a text field on the right scrollpane. I change the value and set the value in the JTree . I am unable to make the edited tree path selected. The methods provided in the API do not seem to work.

    Don't the JTree.makeVisible( ... ) or JTree.scrollPathToVisible( ... ) methods help?
    kind regards,
    Jos
    Edited by: JosAH on Aug 23, 2009 6:19 PM: typo

  • 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

  • JTREE LEAF...PLS help////

    Hm.. i got a problem here.I have created i JTRee and the sub item which is the leaves.How to extend all the leaf node once the Jtree is open

    More dukes please :-)
    Look at the last line that read tree.expandPath(...)
    Note: sometimes DefaultMutableTreeNode.add() and remove() doesn't work well with the JTree so I've changed it to ((DefaultTableModel)jtree.getModel()).insertNodeInto(...) instead
        private void createNodes(JTree tree, DefaultMutableTreeNode top) {
            DefaultMutableTreeNode category = null;
            DefaultMutableTreeNode book = null;
            category = new DefaultMutableTreeNode("Chapter 1 ");
            ((DefaultTreeModel) tree.getModel()).insertNodeInto(category, top, top.getChildCount());
            book = new DefaultMutableTreeNode(new BookInfo("Lesson1-Overview",
            "AD1-1.html"));
            ((DefaultTreeModel) tree.getModel()).insertNodeInto(book, category, category.getChildCount());
            book = new DefaultMutableTreeNode(new BookInfo("Lesson2-Overview2",
            "AD1-2.html"));
            ((DefaultTreeModel) tree.getModel()).insertNodeInto(book, category, category.getChildCount());
            tree.expandPath(new TreePath(category.getPath()));
        }Don't forget the dukes :-)

  • JTree leaf icon

    Hi,
    I am doing a sort of explorer, with a JTree.
    I know how to change icons for leafs, but sometimes my leafs are indeed branches but without nothing in it (an empty directory).
    so the tree displays it as a leaf. But I would like that the tree displays it with the directory icon (but without the "+" sign).
    How can i do this ?
    Sylvain.

    I haven't such problems...
    Ok. You have to create your custom TreeCellRenderer and set it to the tree.
    IconRenderer myRenderer=new IconRenderer ();
    tree.setCellRenderer(myRenderer);
    class IconRenderer extends JLabel implements TreeCellRenderer
    public Component getTreeCellRendererComponent(JTree tree,
              Object value, boolean sel, boolean expanded, boolean leaf,
              int row, boolean hasFocus)
    setText(value.toString());
    //process value (value represents you tree node content)
    if (!leaf) {
    if (expanded)
    setIcon(new ImageIcon("images/expanded.gif"));
    else
    setIcon(new ImageIcon("images/collapsed.gif"));
    else {
    setIcon(new ImageIcon("images/text.gif"));
    MyObject myObj=(MyObject)value;
    if (myObj.isBranch()) {
    setIcon(new ImageIcon("images/branch.gif"));
    regards
    Stas

  • JTree - Mutiple Selection

    Hi
    I have a JTree and whan to enable mutiple selection i.e. the user holds down the CTRL key and selects as many item as s/he wishes. I tried the follow piece of code but it did not work.
    jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    Any suggestions
    Thanks in advance
    Bernie-wolf

    Hi,
    Well, that is the way that you should set the selection model, and the code does work, so there must be something else going on I would guess.
    What exactly is it doing, and what do you expect it to do?
    If you could post a small code snippet that compiles that shows the problem, then people could run it and debug the problem
    Cheers

  • JTree default selection?

    I've tried searching for this here and there but nothing turned up...
    I was wondering if it is possible to set a default selected item on a JTree.
    So that if no nodes are selected - the first item is selected by default.
    Any hints would be greatly appreciated, thanks.

    If for "nested element" you mean "a node", you can use setSelectionPath(TreePath path) and      setSelectionPaths(TreePath[] paths).
    Message was edited by: java_knight

Maybe you are looking for