JTree: editable node

Hello, I want some help because I have a tree and I want to give the user the possibility to change the selected node value ( to have an editable node with a rightclick).
I used this methods :
setEditable (true) and startEditingAtPath()
But I want to get the new value to change the database and reload the tree. How to do ?
thanks

I think I forgot something, Could you say me If I am right ?
I have a popupmenu "rename" for the tree
RenameMenuItem.addActionListener(new ActionListener()
      public void actionPerformed(ActionEvent e)
        Tree.setEditable();
    }); // RenameMenuItem
[\code]
and I have the setEditable method :public void setEditable() {
TreePath treePath = Arborescence.getSelectionPath();
DefaultTreeModel treeModel = (DefaultTreeModel)myjtree.getModel();
treeModel.addTreeModelListener(new MyTreeModelListener());
myjtree.setEditable(true);
myjtree.startEditingAtPath(treePath);
}//setEditable
[\code]
and mytreemodellistener class
class MyTreeModelListener implements TreeModelListener {
  public void treeNodesChanged(TreeModelEvent e) {
    DefaultMutableTreeNode node;
    DefaultMutableTreeNode nodee;
    TreePath path = e.getTreePath();
    node = (DefaultMutableTreeNode)(path.getLastPathComponent());
    System.out.println("node 1 ="+node);
    nodee = (DefaultMutableTreeNode
    try {
      int index = e.getChildIndices()[0];
      node = (DefaultMutableTreeNode)(node.getChildAt(index));
      System.out.println("node 2 ="+node);
    catch (NullPointerException exc) {
      System.out.println("TreeModelListener :"+exc.getMessage());
    String newNode =  node.toString();
    System.out.println("New value: " +newNode);
  public void treeNodesInserted(TreeModelEvent e) {
  public void treeNodesRemoved(TreeModelEvent e) {
  public void treeStructureChanged(TreeModelEvent e) {
}// MyTreeModelListener
[\code]
The "node 1" printing in the MyTreeModelListener is the father whereas I change the child and the "node 2" is the child then I don't know how can I retrieve the old name of the child in my database to change its label .
thanks a lot !                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

Similar Messages

  • 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

  • Set JTree editable

    I use code myTree.setEditable(true); to set JTree node can be editable. The problem is I edited tree node but when I moved cursor, the edited node automatically back to original text. Who can tell me what's happen here, may be need more code to done that. Any help will be really appreciated!

    Well where does you String come from ?
    You have to remember that a String is immutable. That means that the only way to modify a String is to replace it with a modified version of itself. You will "loose" the reference to the String if you have nothing to tie it on. So you need an object (maybe an array, a Vector or an object) to keep a reference to it.
    Let say we want to display persons in a tree.
    Person beeing declared as :
    public class Person {
    public String name;
    public Person(String n) {name = n; }
    public String toString() { return name; } // this is used by the default renderer to display the text for this object.
    Node root = new Node();
    JTree tree = JTree(root);
    root.addNode(new _Node(new Person("Frank")));
    root.addNode(new _Node(new Person("Mike")));
    root.addNode(new _Node(new Person("Bill")));
    root.addNode(new _Node(new Person("Tania")));
    with _Node declared as :
    private class _Node extends DefaultMutableTreeNode {
    public _Node(Object o) {
    super(o, true);
    public void setUserObject(Object userObject) {
    Object obj = this.getUserObject();
    if(obj instanceof Person) {
    ((Person)obj).name = (String)userObject;
    You cannot use a Vector or Array to directly declare you tree otherwise, it will create a tree loaded with DefaultMutableTreeNode which do not behave as you wish.
    Try to experience with the code I just gave you. JTrees are the most difficult swing component to handle. Also take a look at the swing tutorial.
    Hope this helps,
    Anthony

  • Remove background in JTree's node

    How to remove colored background in JTree's node?
    http://www.builder.cz/images/client-tree.gif - here is example how it looks like...

    from reading understand white would be best...
    You may have misunderstood.
    In the image you posted there seems to be a problem with a part that strongly reflects the background for example.
    The »ideal« color for efficient clipping depends on the object being photographed, even a green screen would be problematic with an object of a similar green.
    What is the file format you need anyway? psd with transparency or eps with Clipping Path or …?
    Like Silkrooster pointed out Actions and Image Processor, but also Scripts, can help with automising the task with Photoshop – but quite frankly I expect results so bad that each image would likely have to be checked and improved manually.

  • JTree delete node

    Have a problem with JTree
    A node I call folderNode will normally contain sub-nodes with names lik subnode1,subnode2,subnode3 etc. (Just examples)
    The folder node will then represent the range, so for one with the mentioned subnodes, name would be "subnode1- subnode3".
    To update this foldername after I have deleted say nr 3, I use "theFolderNode.setUserObject("new name here")), and then treeModel.nodeChanged(theFolderNode); I would then expect "subnode1- subnode2". (Don't mind the method of finding the correct label..)
    If I then try to get the new userObject and checking by typing:
    System.out.println(theFolderNode.getUserObject().toString()); - I actually get out what I want, but the label of the FolderNode is still not updated..
    What am I missing here??

    Here is an excert from an article from javaworld
    "The Java programmer must keep in mind that it is the garbage collector that runs finalizers on objects. Because it is not generally possible to predict exactly when unreferenced objects will be garbage collected, it is not possible to predict when object finalizers will be run. Java programmers, therefore, should avoid writing code for which program correctness depends upon the timely finalization of objects. For example, if a finalizer of an unreferenced object releases a resource that is needed again later by the program, the resource will not be made available until after the garbage collector has run the object finalizer. If the program needs the resource before the garbage collector has gotten around to finalizing the unreferenced object, the program is out of luck."
    http://www.javaworld.com/javaworld/jw-08-1996/jw-08-gc.html
    Generally without any tweaking the GC only runs when it has to, so your memory with be recycled then.
    You can call System.gc() but that doesn't cause garbage recycling, but rather tells the JVM that you would like to do it, and then it will do it sometime after that.

  • Jtree custom nodes

    Hi there,
    the "How to Use Trees" tutorial shows how to create simple JTrees where each node is a String:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    I need to have tree structure where each node is like a form entry.
    For example some like this:
    + name: [ ........... ]
    + surname: [ ........... ]
    + child
    ---------+ name: [ ........... ]
    ---------+ surname: [ ........... ]
    and so on...
    The best way that I can think of to do that is to make each node be a JPanel and add to it a JLabel and a JTextField. If this is really the best way to do that then my JTree needs to have something different than DefaultMutableTreeNode as nodes because they can only be used to display Strings.
    So provided there is no better way to do what I want to do, the question is, how do I put a JPanel in a JTree node?

    I think the better way is to use a UserObject giving a summary String in its toString method for standard node display, and to display an extra JDialog for editing all the details of the UserObject if the user chooses to edit the node. Imho, displaying complex nodes directly in the tree tends to confuse the user.

  • JTree hiding nodes

    Hi, I have an extrange problem. It seems that I'm unable to hide nodes with the treeRenderer and I don't know why.
    What I'm looking is to hiding leaf nodes, but leaving the nodes to expand. I don't want them remove because, they could become parents.
    My code is:
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultTreeCellRenderer;
    * @author Victor Manuel
    public class TableTreeRenderer extends DefaultTreeCellRenderer {
        public TablaTreeRenderer(){
            super();
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            if(leaf){
                setVisible(false);
            }else{
                setVisible(true);
            return this;
    NOTE the DefaultTreeRenderer extends a JLabel
    For some extrange reason it doesn't do what it has to do.
    Do you have any clues? please.
    regards,
    Victor Pereira
    Edited by: Darryl Burke -- split a long line of code that was breaking the page formatting in some browsers

    Darryl Burke wrote:
    (untested suggestion) Have you tried returning <tt>null</tt> from the <tt>get...RendererComponent(...)</tt> ?"suggestion" - some virus going round and having infested even the best? That's violating the renderers contract - NOOOO WAAAAYYY!
    and yeah, I'm aware that Swing api doc is severely lacking when it comes to null parameters and return values. And funnily, in a jtable, most ui's cope - mainly because cellRendererPane guards against both null container and null component AND the ui doesn't do much with the component besides passing it over to the rendererPane. Both list and tree fail throw on a null component because they do stuff (like sizing f.i.)
    So children... quickly forget what uncle Darryl told you - he was joking <g>
    CU
    Jeanette

  • About JTree Edit

    Hi all,
    I need implement the funtion:when user select one node and right click,if click 'rename' item in popup-menu,the node selected will enter editing status,and user type some characters then input 'enter' key or click somewhere other than the node,edit is complete,and application get the new value and save to database.
    I has some question when coding:
    1.I find http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#dynamic not work,when edit the node(select and F2) then type some characters and complete,noting happened.how?
    2.how can I catch the event representing edit has completed,so I can save the new name to database?
    Thanks!

    Actually - to simplify the question, I have the following:
    JTree --> UserTreeModel --> UserData
    This is similar to the Genealogy example. So, given a UserData item, how do I find the TreePath for that item in the JTree and start an edit on that Path in the tree programatically?
    Edited by: QetuP on Mar 1, 2008 8:42 AM

  • JTree editing

    I want to start editing of a node, only if the user choose a menu item.
    If the user stops editing the tree shouldn't be editable any more.
    I tried to use the following code
    myTree.setCellEditor(new DefaultTreeCellEditor(myTree,(DefaultTreeCellRenderer)myTree.getCellRenderer())
          public void cancelCellEditing()
            tree.getModel().valueForPathChanged(tree.getSelectionPath(),getCellEditorValue());
            tree.setEditable(false);
        });but the Tree isn't set to editable false, after finishing editing.

    I want to start editing of a node, only if the user
    choose a menu item.
    If the user stops editing the tree shouldn't be
    editable any more.
    I tried to use the following codecancelCellEditing() is called only when the user has canceled the cell editting. For example, the user types a new name, and then pushes escape which will revert back to his old text. This is dependant as to how the cell editor works, but with the default, JTextField, this is called only when someone hits escape, or selects another node in the tree.
    If you put your code in stopCellEditting() is should work better. I don't think you want to call valueForPathChanged inside cancel method. JTree will call valueForPathChanged for you after the editor has properly stopped editting. The CellEditor is responsible for knowing when to stop vs. cancel editting. JTree will handle updating the model.
    That's why your edits are being saved, but the setEditable() method is not being called, because the editor isn't calling cancelCellEditting() which I think is what is leading to your confusion.
    charlie

  • Problem with JTree editing icons

    Hello,
    I want to edit another icons than the default icons in JTree object.
    I look in the javadoc at the several methods, but I do not find a method witch can give me the possibility to setup the collapsed and expanded icon.
    If some one now how to do that, it will be cool.
    Thanks.

    I write this class :
    public class SampleTreeCellRenderer extends TreeCellRenderer
    /** Font used if the string to be displayed isn't a font. */
    static protected Font defaultFont;
    /** Icon to use when the item is collapsed. */
    static protected ImageIcon collapsedIcon;
    /** Icon to use when the item is expanded. */
    static protected ImageIcon expandedIcon;
    /** Color to use for the background when selected. */
    static protected final Color SelectedBackgroundColor=Color.yellow;
    static
         try {
         defaultFont = new Font("SansSerif", 0, 12);
    } catch (Exception e) {}
         try {
         collapsedIcon = new ImageIcon("images/collapsed.gif");
         expandedIcon = new ImageIcon("images/expanded.gif");
         } catch (Exception e) {
         System.out.println("Couldn't load images: " + e);
    public SampleTreeCellRenderer() {
    super();
    public SampleTreeCellRenderer(String collapsedImagePath,String expandedImagePath) {
    super();
         try {
         if (collapsedImagePath!=null) collapsedIcon = new ImageIcon(collapsedImagePath);
         if (expandedImagePath!=null) expandedIcon = new ImageIcon(expandedImagePath);
         } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setCollapsedIcon(String path) {
    try {
    if (path!=null) collapsedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setExpandedIcon(String path) {
    try {
    if (path!=null) expandedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    /** Whether or not the item that was last configured is selected. */
    protected boolean selected;
    public Component getTreeCellRendererComponent(
    JTree tree, Object value,     
    boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
         Font font;
         String stringValue = tree.convertValueToText(value, selected,expanded,leaf,row,hasFocus);
         /* Set the text. */
         setText(stringValue);
         /* Tooltips used by the tree. */
         setToolTipText(stringValue);
         /* Set the image. */
         if(expanded) { setIcon(expandedIcon); }
         else if(!leaf) { setIcon(collapsedIcon);}
    else { setIcon(null);}
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         return this;
    public void paint(Graphics g) {
         super.paint(g);
    } // end of class SampleTreeCellRenderer
    I test it but I do not understand why it do not display the icons.

  • JTree multiple nodes selection problem !

    I can not make my JTree to be in multiple node selection mode.
    I have custom tree model and tree node class, the tree model class
    implements javax.swing.tree.TreeModel, and the tree node is an ordinary
    Java object.
    In this setting, my JTree is always in single selection mode.
    I have tried set the selection model after the JTree has initialized, and
    it didn't work.
    What I missed in TreeModel implementation ? Or should my tree node class
    also implements javax.swing.tree.TreeNode ?
    Don't tell me just call
    xxtree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    It didn't work.

    Just in case anyone wants to know, I did find the magic number of files, and what the problem is. I talked with tech suppot at Adobe, and they know the problem exists, but won't fix it. I did put in a request in the "Request a Feature" form. Read on:
    The magic number is 40 Canon 1Ds Mark III Raw files, and clicking on three or more keywords. The key to not having the numbers of keywords counted incorrectly in the filter pane is to click on the keywords as fast as you can before it starts to write to the metadata. If you click on each keyword one at a time, and wait about a second or more between selecting the keywords, then the counts in the filter panel for the number of keywords is not correct in relation to the number of files that you have chosen to apply keywords to. The cure for this is to click as many keywords as possible as fast as you can before the software starts incorporating the keywords into the metadata.
    I would suggest to Adobe, that a nice feature would be that one could click on as many keywords as one would want, to as many files one would want, and then have a button or icon that would enable one to then apply all the keywords at once, instead of applying them as you click them as it is now. I also would love it if Adobe fixed it now instead of waiting to fix it in the version of CS5. Someone on Adobe's support line told me that Adobe would rather wait to put this into the CS5 version than fix it now. I don't think that is right, but heck, I am only one guy who depends on this software to provide images keyworded to my clients in a timely manner. I would never run my business like this Adobe. If there is a problem, and there is, please fix it now, or give me some of my money back since your product has a design flaw that is having a negative impact in my ability to to my job and run my business.
    Thanks!
    Daniel Root
    Portland, OR

  • Jtree Select node and change leafs icon problem

    Hi All,
    i create a tree and implement a TreeSelectionListener:
    my mission is whenever i select a node i need to change the icon of this node (for now.later i will have to find if it have childrens).
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JTree;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeExpansionListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreePath;
    public class TreeView{
         DefaultMutableTreeNode top;
         JTree tree ;
         Color frameColor;
         public static ImageIcon NoTSelIcon;
         public static ImageIcon SelIcon;
        public static String[] name= new String[8];
         public TreeView(Color BackColor) {
              // TODO Auto-generated constructor stub
            top =  new DefaultMutableTreeNode("Diagnostics");
            this.frameColor=BackColor;
             SelIcon = createImageIcon("../Resource/Images/Select.gif");
             if (SelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
             NoTSelIcon = createImageIcon("../Resource/Images/NotSelc.gif");
               if (NoTSelIcon == null)
                 System.err.println("Tutorial icon missing; using default.");
         public Component createTreeComponents(){
                //Create the nodes.
                 createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            //TREE LISTENERS
            //Treeselction listener
            Handler hObject = new Handler();
            tree.addTreeSelectionListener(hObject);
           //Tree expand/collapse listener
            HandlerExpansionListener hObjectExpan = new HandlerExpansionListener();
            tree.addTreeExpansionListener(hObjectExpan);
    //       tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
            //set tree background
            tree.setBackground(frameColor);
             tree.setCellRenderer(new OverrideTreeCellRenderer(frameColor,SelIcon,NoTSelIcon));
            return tree;
          private void createNodes(DefaultMutableTreeNode top) {
                 DefaultMutableTreeNode category = null;
                 DefaultMutableTreeNode SubCategory = null;
                 DefaultMutableTreeNode SubCategoryBasee = null;
                 DefaultMutableTreeNode SubSubCategoryBasee = null;
                 category = new DefaultMutableTreeNode("Dfe");
                 top.add(category);
                 //Sub test visible
                 SubCategory = new DefaultMutableTreeNode("Test Visible");
                 category.add(SubCategory);
                 SubCategory.add(new DefaultMutableTreeNode("Son 1"));
                 SubCategory.add(new DefaultMutableTreeNode("Son 2"));
                 SubSubCategoryBasee = new DefaultMutableTreeNode("Test Base");
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 1"));
                 SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 2"));
                 SubCategory.add(SubSubCategoryBasee);
          class Handler implements TreeSelectionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeSelect event ");
                        TreePath trph;
                        trph=arg0.getNewLeadSelectionPath();
                        int count=trph.getPathCount();
                        DefaultMutableTreeNode Selnode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                        String Name = (String)Selnode.getUserObject();
                        setSelected(Selnode,true);
                        int number_ofnodes=getNodeCountBelow((TreeModel)tree.getModel() , Selnode, false);
                        System.out.println("The Number of nodes under "+Name+"="+number_ofnodes);
                        tree.setCellRenderer(new IconRenderer(SelIcon,NoTSelIcon,frameColor));
          class HandlerExpansionListener implements TreeExpansionListener {
                   public void valueChanged(TreeSelectionEvent arg0) {
                        // TODO Auto-generated method stub
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)  tree.getLastSelectedPathComponent();
                        if (node == null) return;
                      }     // The inner class
                   public void treeCollapsed(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeCollapsed event ");
                   public void treeExpanded(TreeExpansionEvent arg0) {
                        // TODO Auto-generated method stub
                        System.out.println("treeExpanded event ");
          /** Returns an ImageIcon, or null if the path was invalid. */
             protected static ImageIcon createImageIcon(String path) {
                  //ImageIcon imcon= new ImageIcon(path);
                  //return imcon;
                 java.net.URL imgURL = TreeView.class.getResource(path);
                 if (imgURL != null) {
                     return new ImageIcon(imgURL);
                 } else {
                     System.err.println("Couldn't find file: " + path);
                     return null;
             DefaultMutableTreeNode newnode;
             public void setSelected(DefaultMutableTreeNode Selnode ,boolean isSelected)
                    Enumeration Enchilds=Selnode.children();//ENUMRATE ALL CHILDS FOR THIS NODE
                 if (Enchilds != null)
                      while (Enchilds.hasMoreElements())
                           newnode=(DefaultMutableTreeNode)Enchilds.nextElement();
                           String NameSel = (String)newnode.getUserObject();
                           setSelected(newnode,isSelected);
             //GETTING THE TREE DEPTH
             public int getNodeCountBelow(TreeModel model, Object node, boolean includeInitialNode)
                 int n = includeInitialNode ? 1 : 0;
                 for (int i = 0; i < model.getChildCount(node); i ++)
                     n += getNodeCountBelow(model, model.getChild(node, i), true);
                 return n;
    import java.awt.Color;
    import java.awt.Component;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import javax.swing.Icon;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class IconRenderer extends DefaultTreeCellRenderer {
         private static final long serialVersionUID = 1L;
         Icon SelectedIcon;
         Icon NotSelectedIcon;
         Color BackgroundColor;
         boolean Selected=false;
         boolean Leaf=false;
         boolean IsItaChild=false;
         DefaultMutableTreeNode SelctedNode=null;
        public IconRenderer(Icon SelIcon,Icon NoTSelIcon,Color Bacground) {
             SelectedIcon = SelIcon;
             NotSelectedIcon = NoTSelIcon;
             BackgroundColor=Bacground;
             setBackgroundNonSelectionColor(BackgroundColor);
        public Component getTreeCellRendererComponent(JTree tree,Object value,boolean sel,boolean expanded,
                                                        boolean leaf,int row,boolean hasFocus)
             super.getTreeCellRendererComponent(tree, value, sel,expanded, leaf, row,hasFocus);
             Selected=sel;
             Leaf=leaf;
             DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
             String s2 = (String)node.getUserObject();
       return this;
    }my problem is :
    when i select a node the the method "getTreeCellRendererComponent"
    start to run on the entire tree from buttom to top and than from top to buttom.
    for me it waste of time because if has say 100 nodes it wont botthers me.
    but i have 20000 nodes and more its take a time.
    and for all this nodes i have to make compares.
    is there a way to force the DefaultTreeCellRenderer to not run the entire tree???
    Thanks

    You need to make sure that your TreeModel interprets your group nodes to be non-leaf nodes (one of the methods in the TreeModel interface is called isLeaf). If you are using a DefaultTreeModel with DefaultMutableTreeNode objects, you can use the askAllowsChildren property of DefaultTreeModel and the allowsChildren property of DefaultMutableTreeNode to control this. See the API for more details:
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html

  • JTree making nodes in TreeModel invisible

    I have a TreeModel that represents a database structure. I want to display that structure within a JTree. No problem so far, I just create the JTree using theTreeModel. Everything works great.
    Now, I want some nodes in the tree (tables in the structure) to not be visible to the user, but I cannot remove them from the model. I need the entire db structure intact within the model so all my processing works correctly, but there is no need for the user to be aware of the entire structure.
    Anyway, have any ideas?
    Thanks a bunch.

    Try extending DefaultMutableTreeNode and just had it
    return the count and children of the 'visible' nodes.More info... And maybe add methods getRealChildCount() and getRealChild(int i) so you can manipulate them internally.

  • JTree adding nodes

    Hello all,
    I have two questions concerning Trees,
    1. I have created the Tree by the JTree(Vector) method, initially the vector does have some elements but i have to add some more later, so when my vector gets updated how can I add the same element to the tree in the form of a node?
    2. The Tree being created like this, has automatically generated names for the nodes (i guess it shows the memory address) but i want to change the name of all of my nodes, what is the method for renaming nodes?

    There are two pieces of Trees that you have not yet found. The first is the TreeModel, which is accessible through myTree.getModel(). You can use this model to create the data structure; the JTree object is simply a view of that model.
    The second piece is the TreeCellRenderer, accessible through myTree.getCellRenderer(). This renderer is used to draw the nodes of the tree and, by default, one is used that renders the Strings returned by the toString() method of the objects in the model. To display different strings, you can either (1) replace the renderer or (2) override the toString() method on the objects in your model. The first is recommended if the strings vary radically from the desired result of toString() or if toString() is being used for something else; the second is recommended for simplistic models or for situations in which the display properly reflects the nature of the object.
    Replacing the renderer also allows you to use any JComponent for rendering you wish. This can give you the ability to present gradient backgrouns, dynamically loaded icons, etc.
    Many objects in Swing use this format in which there are three portions of an object: the view (which is the standard object, like an instance of JTree, JList, or JTable), the model (which contains the actual data structure), and the renderer (which acts like a rubber stamp to draw the objects without causing more than one object to be instantiated to render thousand-element lists).

  • JTree - Create nodes and expand

    Hi there,
    I have made a file-tree from the swing jtree, where My Computer is the root, then C:/ etc, Program Files, etc...
    The problem I'm having is that I'm trying to open up a node if a link has been clicked. For example.. if A shortcut to C:/Program Files/Pictures/pic.jpg was clicked, then it should go the C:/ node, create it's children, and expand it, go to Program Files node, create it's children and expand it, etc until pic.jpg is visible.
    TreePath x = new TreePath(ta);
    TreePath y = x.pathByAddingChild(myComputer);
    TreePath z = y.pathByAddingChild(programFiles);
    tree.expandPath(y);
    The above is the general idea of what I'm trying... I can't see why this doesn't work. (ta is empty root folder, then myComputer and programFiles are other treenodes).
    Any ideas?
    Thanks.
    David

    Create your TreeModel using the FileSystem as the underlying data store, as shown in this article:
    http://java.sun.com/products/jfc/tsc/articles/jtree/
    The use JTree#setAnchorSelectionPath when the user clicks on a file to select that item in the tree. Also look at JTree#scrollPathToVisible if your JTree is in a scroll pane.

Maybe you are looking for