JTree#expandRow() Question

JTree tree;
//etc...
1) /** Expand the tree */
for (int i=0; i<tree.getRowCount(); i++)
     tree.expandRow(i);
and tree.getRowCount() = 6
2) /** Expand the tree */
for (int i=0; i<6; i++)
     tree.expandRow(i);
My tree has 6 rows, and each row has its own sub-tree hierarchy.
I wonder why the first case will expand the whole tree, which includes
the subtrees of each row.
But in second case, it only expands the first 6 rows in the tree.
So basically the question is why (1) and (2) have different tree view outputs??

Well, after you expand row 1, the row count isn't 6 anymore, is it? It's something larger than that, depending on how many children the first node has.

Similar Messages

  • JTree#expandRow() Problem

    JTree tree;
    //etc...
    1) /** Expand the tree */
    for (int i=0; i<tree.getRowCount(); i++)
         tree.expandRow(i);
    and tree.getRowCount() = 6
    2) /** Expand the tree */
    for (int i=0; i<6; i++)
         tree.expandRow(i);
    My tree has 6 rows, and each row has its own sub-tree hierarchy.
    I wonder why the first case will expand the whole tree, which includes
    the subtrees of each row.
    But in second case, it only expands the first 6 rows in the tree.
    So basically the question is why (1) and (2) have different tree view outputs??

    Cross-post: http://forum.java.sun.com/thread.jsp?thread=327285&forum=31&message=1329704

  • JTree sizing question...

    Hello:
    I have a JTree for which each cell contains a button. I have written a renderer that renders the button, and I realize that I have to do some special stuff to capture a click on the button. My question is unrelated to all of that.
    The problem is that over time, the labels on my buttons change (and may become longer (wider)), but the tree size does not change. In fact, when I update the button label and the tree is re-rendered the rendering of the button gets "chopped off". I've put the tree in a scroll pane, but this doesn't help - the right side of some of the buttons get cut off to the original tree size. I've tried lots of different variations on setPreferredSize, calling repaint, etc, and am not having any luck. I've put together a demonstration of this behavior in a smallish application that I'm posting here, where I create a 2 node tree with buttons that read "Hi", then I change the button labels to "Goodbye" and re-render. You'll see that the button's are cut off about halfway through the button.
    In case its important - I'm running java version 1.5.0_07 on a 32-bit Linux box.
    Any help would be greatly appreciated. Thanks in advance!
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class JTreeQuestion
      public static void main(String [] args)
        JTreeFrame f = new JTreeFrame();
        f.pack();
        f.setLocation(30, 30);
        //Draws buttons with "Hi" (short string)
        f.setVisible(true);
        ButtonNode.updateString("Goodbye");
        //Draws buttons with longer string, buttons get "cut off"
        f.repaint();
    class JTreeFrame extends JFrame
      JTree tree;
      JScrollPane treeView;
      public JTreeFrame()
        super("My Tree");
        DefaultMutableTreeNode root;
        root = new DefaultMutableTreeNode(new ButtonNode());
        root.add(new DefaultMutableTreeNode(new ButtonNode()));
        tree = new JTree(root);
        tree.setCellRenderer(new ButtonNodeRenderer());
        treeView = new JScrollPane(tree);
        add(treeView);
    class ButtonNode
      public static String str = "Hi";
      public static void updateString(String inStr)
      { str = inStr; }
      String getStr()
      { return str; }
    class ButtonNodeRenderer extends DefaultTreeCellRenderer
      public Component getTreeCellRendererComponent(JTree tree,
                              Object value, boolean sel, boolean expanded,
                              boolean leaf, int row, boolean hasFocus)
        Box theBox = new Box(BoxLayout.X_AXIS);
        super.getTreeCellRendererComponent(tree, value, sel, expanded,
                                           leaf, row, hasFocus);
        DefaultMutableTreeNode jtreeNode = (DefaultMutableTreeNode)value;
        theBox.add(new JButton(((ButtonNode)jtreeNode.getUserObject()).getStr()));
        return (theBox);
    }

    For those who are interested. The DefaultTreeModel has a method named nodeChanged() that tells the tree model that a specific node has changed, and the model re-interprets the cell causing its sizse to change as necessary, so that the full button is rendered now.
    Basically what I did was instead of calling repain, I call a method that I wrote that loops through all the tree nodes, indicates they have changed, then repaint's, and it all works out. My trees are relatively small, so this is fine, but if others face the same problem, you'll probably want to selectively indicate which nodes have changed so the tree model doesn't have to do more work than necessary.

  • JTree image question

    I have a question about using images in a JTree.
    I have like 2 parent nodes who both have a lot of child nodes now i know how to get an image for every node but how do i get 1 image for 1 parent with all his children and another image for the other parent with his children.

    It is a programming problem because i dont know how to give echt DefaultMutableTreeNode his own picture. You should think of it like msn when you log in your contacts are in a Tree and your offline contacts have a red icon and online contacts have green one. I need to to the same for my program(chat program). But i can't figure out how but i know how to give alle the DefaultMutableTreeNode's a picture but i cant give individual one's a picture.
    I hope i cleared things up :)

  • JTree Updating question

    Hi there. I have two questions.
    I have a data structure that is being displayed in a JTree, so I made a Model and it works great. The data structure can be updated from non-gui interaction. The nodes don't change position or anything, its just the data that is displayed is changed. I handle it currently by calling a function in the model I made called nodesChanged(), which basically does the following:
    public void nodesChanged()
        int len = treeModelListeners.size();
        TreeModelEvent e = new TreeModelEvent(this, new Object[] {rootItem});
        for (int i = 0; i < len; i++) {
          ( (TreeModelListener) treeModelListeners.elementAt(i)).treeNodesChanged(e);
      }It does actually work, the changes are reflected in the JTree, but it seems a little expensive, and the updates to the actual data model could come at about 150 per second. To deal with that now, I just use a timer class that updates it about every 3/10's of a second, which does a pretty good job, but is there a more elegant way to do this? Something where the node is an observer of the data in the data structure (which are Observable objects)?
    The second question I have is when I do the above, sometimes the display name of the node will be larger than the value it had previously, but the Textbox (if that's what it is) doesn't grow, so I get a ... at the end.
    For example, if I have "Run" and it changes to "Stopped", it will show up as "Sto...".
    Any help would be great. TIA.

    well, you can start by making the node you put in the tree model event the lowest node in the tree that needs updating, instead of root.
    I don't know about the timer thing, cuz as far as I know, the listener will invoke code that will refresh the renderers, as opposed to painting where repaint calls can be merged into one. If you aren't getting that many updates all the time, you could implement something where the listener fires to an intermediate listener which will fire the info to the tree after a slight delay. That way if you get multiple updates, you can effectively ignore lots of them.
    The ... thing, I thought that treeNodesChanged was the appropriate method, although maybe it has to be for the specific node, not root.

  • JTree event question

    Hi,
    I am facing a problem and hoping somebody here can give me a clue.
    I have a JTree in my application, which has different types of nodes (all implement TreeNode ). One node there needs lazy-loading, what I want is when user clicks either '+' or folder icon/label then this node gets updated. I have added MouseListener to the tree, it works fine with clicking folder icon or label but not for clicking '+'. I also tried adding other listeners like TreeWillExpand etc. but it not seems a good solution to me since I just need to treat one node defferently.
    There are a couple of options I think can help:
    - catch clicking '+' event for specific node
    - display '+' even folder has no child (just for one node)
    - or disable '+' for this node
    Thank you in advance

    Well, after you expand row 1, the row count isn't 6 anymore, is it? It's something larger than that, depending on how many children the first node has.

  • JTree path question

    I have created a program that basically simulates single celled organisms in a random (non graphical) world, and I want to use a JTree to show the family history and allow the user to bring up an organism's stats by clicking on in the the Jtree, but I have a problem. Each organism has a unique ID number (starting at 0) and that's what I want to display on the tree. I have the code working to add the new organisms to the root, but I want them added as a child to the parent (each child has only one parent for these organisms), but I don't know how to do it. I tried using insertNodeInto but since everything after the root is dynamically generated I don't know how to identify the parent correctly (just using the ID doesn't seem to do anything). Do I need to create a method that somehow copies the entire treemodel into a collection and steps through it? I have the organisms in a collection already (an arraylist to be exact), so I could figure out the lineage by stepping through that, but then how do I build a 'selection path' object that will work to tell Java exactly where I want the child to go? Is the selection path just some kind of array, or is it even possible to build a selection path without a user clicking on a tree node? I hope you can figure out what I'm trying to say here and I appreciate any help you can give.

    Start by creating a Map that has your organisms as the key and the nodes they are in as the value. Or just let the organism include a reference to the node that contains it. Either of those would allow you to identify the TreeNode that contains a particular organism.

  • Jtree - beginner question

    hi,
    i wanted to build a jtree and have started the swing tutorial on it, seems small, but i wanted to know is it easy to build a jtree to map the file system? something like windows explorer? i wanted to build a ftp utility and wanted to show the local and remote drives and file systems in a scroll pane, so i was thinking about using a jtree, first time i've had to use it, so i'm a little new to it.
    Thank you.

    Search Google for "java file explorer"
    --A                                                                                                                                                                                                                       

  • JTree Icon question

    Currently, ALL leaves in the JTree are displayed with a certain icon that looks like a piece of paper. What should I do if I want only leaves at depth 4 to have the piece of paper icon and all the rest to have folder icons even if they are leaves?
    Thanks

    I guess a custom renderer is in order.
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#display

  • JTree Important Question

    Hi All,
    in the JTree, is there a way to change the root handles
    icons, not through the UIManager?
    I need the Changes to apply only for the one instance.
    is there a key for the putClientProperty method?
    a work around through the TreeCellRenderer is possible to
    write, but seems as a bit of a waste.
    10x in advance

    OK. If "handle" means the leftmost icons, that is the little circle with a dash pointing right or down under Java L&F, or either a + or a - in a square under Windows & Motif L&F, they are NOT part of the node display, and so they are not dealt with by a renderer. They are completely L&F dependant (while the leaf, open, closed are renderer dependant, and the L&F just provides some "hint" to the default renderer). It is possible that some L&F would display trees in a completely different way, without handles. So this is the tree UI delegate business, not the renderer's.
    You can set the icons for the application globally by setting UIManager properties Tree.expandedIcon and tree.collapsedIcon. (you knew that already). The good news is that the UI delegate seems to get these icons once sometime when it is created, rather than asking the UIManager each time it needs them.
    I tried
        Object previousExpanded = UIManager.put("Tree.expandedIcon", myExpandedIcon);
        Object previousCollapsed = UIManager.put("Tree.collapsedIcon", myCollapsedIcon);
        tree2 =  new JTree(data);
        UIManager.put("Tree.expandedIcon", previousExpanded);
        UIManager.put("Tree.collapsedIcon", previousCollapsed);.
    There is a tree1 created before and a tree3 afterwards, and it works fine, that is only tree2 get my icons.
    I tried to go a little farther, as I am not sure when the ui delegate might get reset. So I wrote a descendant of JTree to do the job in updateUI.
    public class CustomHandleTree extends JTree {
      // republish ancestor non-default constructors
      Icon expanded = null;
      public void setExpandedIcon(Icon anIcon) {
        expanded = anIcon;
        updateUI();
      // do the same for collapsed
      public void updateUI(){
        Object defaultExpanded = null;
        if (expanded != null)
          defaultExpanded = UIManager.put("Tree.expandedIcon", expanded);
         // collapsed stuff too
         super.updateUI();
        if(expanded != null)
          UIManager.put("Tree.expandedIcon", defaultExpanded);
         // collapsed stuff too
    }It works too, and I can even set the handles dynamically, when clicking on some button. It refreshes properly.
    The bad news is that I found that by trial and error, and have no single line of documentation to explain why it should work.
    Hope it helps nevertheless.
    Regards.

  • JTree Renderer Question

    Hi,
    i want to change the icon of a particular leaf when the user double click it, but i dont want to change the rest of the other leafs icons i want them to keep the icon they have
    can this be posible??
    thank you

    create your own renderer.
    Search for "MyRenderer" on this page:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

  • Jtree item question

    Hi,
    I'm new to Java coming from C++ background, I can't seem to find a method to retrieve the currently selected tree item.
    The closest method I can see is getLastSelectedPathComponent()
    Object tmp = treeMenu.getLastSelectedPathComponent();
        try {
            if (tmp.toString().equals("some text")) {...but that seems to return always the root node.
    What am I missing ?

    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#select

  • JTree listener question

    Hi,
    What are the TreeListener/TreeModel methods that would be called if I
    1. double click on a row
    2. expand/collaps a node
    Thanks in advance.
    Olek

    A quick summary:
    TreeModelListener
    treeNodesChanged
    treeNodesInserted
    treeNodesRemoved
    treeStructureChanged
    TreeExpansionListener
    TreeWillExpandListener
    ExpandVetoException
    TreeSelectionListener

  • JTree selection questions

    I am wanting a user to select multiple top level folders in the tree.
    Do I simply have the user ctrl select multiple folders? Or is it possible to place a checkboxes next to the tree items?
    If I have a button that trigger a function. How does that function know what items were selected in the tree?

    http://java.sun.com/docs/books/tutorial/uiswing/events/treeexpansionlistener.html
    OR
    let the JPanel that contains the tree implement MouseListener
    then
         public void mouseClicked(MouseEvent e) {
              // right-click?
              if (e.getButton() == MouseEvent.BUTTON3)
                   return;
              int x = e.getX();
              int y = e.getY();
              TreePath selPath = tree.getClosestPathForLocation(x, y);
              if (selPath == null)
                   return null;
              DefaultMutableTreeNode nodeClicked = (DefaultMutableTreeNode) selPath.getLastPathComponent();
              Rectangle rect = tree.getPathBounds(selPath);
    if(rect.contains(x,y))
    //you get the idea...
    }

  • Reload JTree and keep expanded nodes

    Hi all,
    I have spent some time looking around on this, found some useful stuff, but I still cannot seem to get a result.
    Here is my situation:
    I have a JTree for a GUI desktop app. I build the tree from a database file. The user has the ability to refresh the tree to keep it in sync with any database changes. The problem is that when I refresh, all the nodes that were previously expanded are now collapsed again.
    Having looked around, I have seen a lot of JTree.expandRow() answers, but I don't want to use expandRow, as the rows will changes according to any db changes.
    I thought a good solution would be to trap any expand or collapse events and for each either add or remove the TreePath for the relevant node onto a List. When the users refreshes the tree, I thought I could run through the list and expand any TreeNodes I find. I also found someone advocating such an approach in another thread. BUT - it doesn't work for me Here is the code for my refresh. Any help/advice, greatly appreciated.
    Thanks in advance,
    Steve
    private void refreshBrowser(){
            System.out.println("Refresh browser - Started");       
            rootTreeNode.removeAllChildren(); // remove all nodes from root
            loadBrowserData(); // This method loads nodes from a database
             Iterator<TreePath> TPI = objectTreePaths.iterator(); // run throught my saved paths
            while (TPI.hasNext()) {
                TreePath yTreePath = TPI.next();           
                browserTree.expandPath(yTreePath); // Expand each found path
            treeModel.reload(); // model changed - reload it.
            System.out.println("Refresh browser - Complete");       
        }

    Here is my situation:
    I have a JTree for a GUI desktop app. I build the
    tree from a database file. The user has the ability
    to refresh the tree to keep it in sync with any
    database changes. The problem is that when I refresh,
    all the nodes that were previously expanded are now
    collapsed again.
    Having looked around, I have seen a lot of
    JTree.expandRow() answers, but I don't want to use
    expandRow, as the rows will changes according to any
    db changes.you could use:
    JTee.scrollPathToVisible(path);
    Where path is obtained in this way from a DefaultMutableTreeNode (TreeNode):
    TreePath path = new TreePath(((DefaultMutableTreeNode)node).getPath());
    I thought a good solution would be to trap any expand
    or collapse events and for each either add or remove
    the TreePath for the relevant node onto a List. When
    the users refreshes the tree, I thought I could run
    through the list and expand any TreeNodes I find. I
    also found someone advocating such an approach in
    another thread. BUT - it doesn't work for me When you perform a JTree.reload() call, it will collapse each node.
    My advice is to call JTree.reload() and then call JTree.scrollPathToVisible(path) for each TreeNode previously expanded.
    Hope this can help,
    regards

Maybe you are looking for

  • Can I send a iMovie home movie through iMessage?

    I made a home movie using iMovie (OS X Snow Leopard), exported it to iTunes (lastest version), and shared the movie to my iPhone 4S (latest iOS update). Now I want to send the movie via iMessage (both parties on Wi-Fi). However, the home movie shows

  • BASE UOM different in R/3 and APO

    Hi Experts I am working in a scenario where we have 2 R/3 boxes connected to 1 APO. The products are common across the boxes but locations are different. We are implementing GATP with Rules based substitutions for locations across the R/3 boxes. Sinc

  • Export workbooks in discoverer plus

    hi I am not able to export discoverer workbook as .dis from discoverer plus. how to do this Should I follow only command prompt? From discoverer admin i am able to export a workbook as .eex ..But i wonder how to import this workbook.eex into discvere

  • Invalid extension descriptor - Licensing AIR for Android devices

    I'm trying to do licensing app according to this article http://www.adobe.com/devnet/air/articles/android-licensing-native-extensions.html. If i try to generate the ANE file in ADT command prompt then displays this error - Invalid extension descripto

  • I have followed all the directions for downloading but have not been able to download Photoshop.

    I have followed all the directions for downloading but have not been able to complete the downloading.   Message was "Adobe Application Manager failed to install.