Repopulate JTree

Hi! I've a JTree which I populate the first time with some DefaultMutableTreeNode objects. When an user clicks a button in my GUI, I perform cerain operations, and need to reset that JTree and add new DefaultMutableTreeNode objects to it.
This JTree is inside a JScrollPane. What I'm doing right now, when the users clicks the button is calling the removeAll on JTree and removeAllChilren on the root DefaultMutableTreeNode. Then add to the root DefaultMutableTreeNode the new objects, and then adding that root to my JTree.
After that I call revalidate and repaint on the JTree but nothing is happening. It doesn't remove the previous nodes, and certainly, does not put the new ones.
I'm getting no exceptions at all, so I suppouse that in some place i'm missing a refresh or something.
Hope you can help! Regards

model.reload();If that doesn't work then try creating a completely new model and use the setModel(...) metthod.

Similar Messages

  • Problem Expanding certain paths in a JTree

    I am working with a JTree and trying to do the following:
    My JTree is initially defined using the following code:
    rootNode = new DefaultMutableTreeNode();
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    tree = new JTree(treeModel);
    //treeListener = new TreeSelectionListener();
    tree.addTreeSelectionListener(treeListener);
    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
    renderer.setLeafIcon(null);
    tree.setCellRenderer(renderer);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setShowsRootHandles(true);
    tree.setAutoscrolls(true);
    tree.setExpandsSelectedPaths(true);
    When a user selects a node, and presses some button, I get and save the current path (of the selected component) like this:
    TreePath currentPath = tree.getSelectionPath();
    Then I do some action on it, then repopulate the JTree
    I have the following code at the bottom of the JTree populating method in an effort to expand the path in the tree which was last selected:
    tree.expandPath(currentPath);
    tree.setVisible(true);
    tree.updateUI();
    The problem is that when the tree repopulates, it stays completely collapsed, and I can't seem to figure out how automatically make it viewable in an expanded state (I don't want the user to have to go expand each expandable node by clicking beside it)
    Does anyone know how to either expand the whole tree from the very beginning, or expand just the selected path?
    Thanks in advance for your help,
    Noha

    To expand on path there is jtree.expandPath(treepath);
    To expand the whole tree, I wrote a recursive method.

  • Reloading JTree and expanding last selected rows

    I'm working on an applet that loads the nodes of a JTree from a database. When a node is selected, its data are displayed in a different panel. When a "reload" button is clicked, all the nodes in the JTree are removed except for the root node, and the JTree is recreated from the database. I'm try to get the new JTree to expand and select the rows that were selected before reloading, but I can't get this to work.
    Before removing the nodes, I save the currently selected row numbers using JTree.getSelectionRows(). After recreating the JTree, I re-select the previously selected rows and try to expand them:
    // tree is the name of the JTree.
    tree.setSelectionRows(selected);
    for (int i= 0; i < Array.getLength(selected); i++) {
                System.out.println("selected row: " + selected);
    tree.scrollRowToVisible(selected[i]);
    tree.updateUI();
    The previously selected rows do not automatically become visible in the resulting JTree. I also tried using tree.expandRow instead of scrollRowToVisible, with the same results.
    Any help would be appreciated!

    I think part of your problem is this...
    When you repopulate your tree, and only the root node is visible, getRowCount() will return 1. When you call expandRow(x) where x > 1, the result is basically a no-op (nothing happens). This is the correct behavior for these methods.
    In other words, I think you need to come up with a whole new algorithm.
    Let's assume you have a tree that looks like...
    Node 0
    |__________Node 0.0
    |               |__________Node 0.0.0
    |
    |__________Node 0.1
    |__________Node 0.2
                     |__________Node 0.2.0
                     |__________Node 0.2.1Try this...
    //save the current open/closed state of the tree and selection state
    Vector<Integer> selectedRows = new Vector<Integer>();
    Vector<Boolean> openClosed = new Vector<Boolean>(tree.getRowCount());
    openClosed.setSize(tree.getRowCount());
    for( int i = 0; i < tree.getRowCount(); ++i )
       if( tree.isExpanded(i) )
            openClosed.set(i,true);
       else
            openClosed.set(i,false);
       if( tree.isRowSelected(i) )
           selectedRows.add(i);
    //at this point we have all the needed state information
    // rebuild to tree from the database now
    // then do this
    int rowIndex = 0;
    while( rowIndex < tree.getRowCount() )
        if( openClosed.getElementAt(rowIndex).booleanValue() == true )
             tree.expandRow(rowIndex);
             // note that if a row gets expanded, getRowCount() will increase
        ++rowIndex;
    // at this point, your tree should be expanded exactly as it was before the reload
    int[] rows = new int[selectedRows.size()];
    int index = 0;
    for( Integer i: selectedRows )
       rows[index++] = i;
    tree.setSelectionRows(rows);
    // at this point the tree should have the same selection as before the reload.I hope this helps. Please reward me the Duke Dollars if it does. Not awarding the Duke Dollars kills the system (which is an honor system). A dead system hurts us all.
    P.S. I guess I never referenced the little tree I drew. Oh well. It looks great doesn't it?

  • Exist a Jtree node.id or something like this ?

    I would want to retrieve a node using a unique 'id', for example the absolute index (into the total nodes count)
    Is there something like this ?
    Can I add a particular property to a node ? ( for example this 'id' if it does not exist )
    Another question :
    If I want to implement a search code, this 'id' can be useful, or must I transverse the whole Jtree
    Thanks

    Hello.
    Do the following:
    1. Go to the Apple Menu at the top left of the screen
    2. Select Software Update...
    3. Install any updates that are found.
    If the Amazon issue continues after these updates, then do this:
    1. Open Safari
    2. Erase any web address you have currently showing (for example www.apple.com or www.google.com)
    3. Type in www.amazon.com
    4. That should take you directly to amazon.com
    It should look like this in your Safari::

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • Expanding a JTree Node on selection

    Hi,
    I have a need to expand the node on selection in a JTree. I would like all the children to be recursively expanded and selected.
    I believe the code lies somewhere with in JTree's TreeSelectionListener.
    The code I have is as follows
    tree.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent evt)
    TreePath[] paths = evt.getPaths();
    for (int i=0; i<paths.length; i++)
    if (evt.isAddedPath(i))
    DataNode node = (DataNode)paths.getLastPathComponent();
    ArrayList aList = node.children();
    if( !aList.isEmpty() )
    for(int j = 0; j<aList.size(); j++)
    TreePath tp = paths[i].pathByAddingChild(aList.get(j));
    System.out.println(tp);
    tree.expandPath(tp);
    }//for
    }//public void ValueChanged
    This does not seem to solve the problem..
    Your comments or help is very much appreciated..
    thanks
    S

    it does work for me (i do it in an action). what doesn't work for you?
    thomas
      public RecursiveExpander() {
        menu = new JPopupMenu();
        JMenuItem expand = new JMenuItem("Expand Recursive");
        expand.addActionListener(this);
        menu.add(expand);
      public void mousePressed(MouseEvent e) {
        theTree = (JTree)e.getSource();
        currentPath = theTree.getPathForLocation(e.getX(), e.getY());
        if ((currentPath != null) &&
            !((TreeNode)currentPath.getLastPathComponent()).isLeaf() &&
            (e.getModifiers() == InputEvent.BUTTON3_MASK)) {
          menu.show(theTree, e.getX(), e.getY());
      public void actionPerformed(ActionEvent ae) {
        new Thread(this).start();
      public void run() {
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try { expand(currentPath); }
        catch (OutOfMemoryError oom) {
          System.gc();
          System.err.println("RecursiveExpander: " + oom);
          JOptionPane.showMessageDialog(null, "RecursiveExpander: " + oom, "Error", JOptionPane.ERROR_MESSAGE);
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      private void expand(TreePath path) {
        theTree.expandPath(path);
        TreeNode start = (TreeNode)path.getLastPathComponent();
        for (int i = 0; i < start.getChildCount(); i++) {
          TreeNode node = start.getChildAt(i);
          if (!node.isLeaf()) {
            expand(path.pathByAddingChild(node));
    }

  • Rename a Jtree node directly & Popup Menu

    Pls assist with codes to rename a Jree node directly without using a dialog box or optionpane. I tried
    tree.startEditingAtPath(/* path of selected node*/);
    to go to edit mode and it does not work.
    II. Is it possible to attach different popmenu to the root, separate from the parent and child? Pls assist with code as the popupmenu i use at the moment shows up on the nodes(root, parent, leaf).
    I have benefiited greatly from questions asked and answers proferred at this forum and I use this opportunity to thank everyone greatly as I have migrated to Java based on all the materials sourced on the net.
    [email protected]

    public class AutomatedTreeMouseHandler extends MouseAdapter {
         public void mousePressed(MouseEvent e) {
              JTree tree = (JTree) (e.getSource());
              int x = e.getX();
              int y = e.getY();
              TreePath path = tree.getPathForLocation(x, y);
              if (path != null) {
                   // generate your popup here
    Dennis,
    are you saying that i have to define the popmenu for each category of node in the mouseadapter and att'd these to the tree depending on whether root, leaf or whatever type of node is selected?
    I will try this and revert.
    I can not make anything out of the reference giving with regard to renaming a node in edit mode.
    Pls provide more explanation and sample code, if necessary.
    Thanks a million.

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • Problem in Jtree while retrieving values from a hashtable

    Hi
    I am trying to show some values in a Jtree.I am receiving the values in a hashtable.The hashtable contains unique key but duplicate values.i want to show that values of that hashtable in a tree(but unique values)and under each value show all the key of it.can you please tell me how to do that.
    thanks

    If i understand right, you want to do something like this:
                   Hashtable values = yourhashtable;        
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("Values");
              HashMap<Object, DefaultMutableTreeNode> nodes = new HashMap<Object, DefaultMutableTreeNode>();
              Iterator ii = values.keySet().iterator();
              while (ii.hasNext()) {
                   Object key = ii.next();
                   Object value = values.get(key);
                   if (nodes.containsKey(value)) {
                        DefaultMutableTreeNode node = nodes.get(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                   } else {
                        DefaultMutableTreeNode node = new DefaultMutableTreeNode(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                        nodes.put(value, node);
                        root.add(node);
              JTree tree = new JTree(root);Hope this helps,
    Alex.

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

  • Problem with JTree

    Hi All,
    Can anyone please help me in writing a method which will take a JTree/TreeNode/MutableTreeNode and a string as parameters, and then search the JTree/TreeNode/MutableTreeNode for that particular string (which will be the name of a node/leaf in the tree), and then expand the JTree to show the node/leaf?
    Thanx a lot in advance,
    Best Regards,
    Debopam.

    Here's something:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class Test extends JFrame {
        private TreePanel treePanel;
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (treePanel = new TreePanel ());
            getContentPane ().add (new SearchPanel (), BorderLayout.SOUTH);
            pack ();
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public Dimension getPreferredSize () {
            return new Dimension (600, 600);
        private class TreePanel extends JPanel {
            private DefaultTreeModel model;
            private JTree tree;
            public TreePanel () {
                model = new DefaultTreeModel (createRoot ());
                tree = new JTree (model);
                tree.setRootVisible (false);
                tree.setShowsRootHandles (true);
                setLayout (new BorderLayout ());
                add (new JScrollPane (tree));
            private TreeNode createRoot () {
                DefaultMutableTreeNode root = new DefaultMutableTreeNode ("");
                add (root, 1, 3);
                return root;
            private void add (DefaultMutableTreeNode node, int i, int n) {
                for (int l = 0; l < 26; l ++) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode (((String) node.getUserObject ()) + (char) ('a' + l));
                    if (i < n) {
                        add (child, i + 1, n);
                    node.add (child);
            public void searchAndExpand (String text) {
                TreeNode[] path = search ((DefaultMutableTreeNode) model.getRoot (), text);
                if (path != null) {
                    TreePath treePath = new TreePath (path);
                    tree.scrollPathToVisible (treePath);
                    tree.setSelectionPath (treePath);
            private TreeNode[] search (DefaultMutableTreeNode node, Object object) {
                TreeNode[] path = null;
                if (node.getUserObject ().equals (object)) {
                    path = model.getPathToRoot (node);
                } else {
                    int i = 0;
                    int n = model.getChildCount (node);
                    while ((i < n) && (path == null)) {
                        path = search ((DefaultMutableTreeNode) model.getChild (node, i), object);
                        i ++;
                return path;
        private class SearchPanel extends JPanel {
            public SearchPanel () {
                JTextField searchField = new JTextField (10);
                searchField.addActionListener (new ActionListener () {
                    public void actionPerformed (ActionEvent event) {
                        treePanel.searchAndExpand (((JTextField) event.getSource ()).getText ());
                setLayout (new GridBagLayout ());
                add (searchField, new GridBagConstraints ());
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

  • Problem with Jtree to xml tranform..how to set/get parent of a node?

    Hi,
    I am trying to develop xml import/export module.In import wizard, I am parsing the xml file and the display it in Jtree view using xml tree model which implements TreeModel and xml tree node.I am using jaxp api..
    It is workin fine.
    I got stuck with removal of selected node and save it as a new xml.
    I am not able to get parent node of selected node in remove process,itz throwing null.I think i missed to define parent when i load treemodel.Plz help me out..give some ideas to do it..
    thanks
    -bala
    Edited by: r_bala on May 9, 2008 4:44 AM

    there's no way anyone can help you without seeing your code.

  • Problem with JTree while expanding/collapsing a node

    Hi,
    I'm using a JTree for displaying the file system.
    Here, i want that whenever a node get expanded,
    it should show the latest files/directories under that node.
    Now, what i'm doing is, getting all the files/dir's using files.listFiles(),
    under that node and then creating a new node and adding it to parent (all in expand() method).
    But, now the problem is, while doing this whenever the parent node get expanded its adding all the latest files/dirs into the previous instance
    resulting the same file/dir is displaying twice,thrice.. and so on, as that node is expanded and collapsed.
    i tried removeAllChildren() in collapse() method but then that node is notexpanding at all .
    Can anybody help me please...
    i got stuck b'coz of this only.
    Thanks...

    Now what i'm doing is every time expand() get called,
    i'm comparing all the children of that node in the
    current instance with all the children present in the
    file system (because there is a possibility that some
    file/dir may be added or deleted)
    is this the right wy or not?it certainly is not wrong, but as usual, there is more than 1 way to implement this...
    b'coz right now i'm getting all the files/dirs that
    are newly added but facing some problem if somebody
    deletes a file/dir.
    i'm still trying to get the solutionthen you should not just compare all the children of the node with the files/dirs but also the other way round. compare the files/dirs with the children to determine if the file/dir still exists and if not remove the node.
    or you could check if the file which a node represents exists and if not remove the node.
    thomas

  • Problem with JTree custom renderer when editing

    I have a JTree which uses a custom renderer to display my own icons for different types of nodes. The problem I am having is when I setEditable to true and then attept to edit a node the icon switches back to the default icon, as soon as I am done editing it goes back.
    What I am doing wrong?

    Here is my rendererer
    public class DeviceTreeRenderer extends DefaultTreeCellRenderer implements GuiConstants {
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          JLabel returnValue = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
          if (value != null) {
             returnValue.setToolTipText(value.toString());
          if (value instanceof Device) {
             returnValue.setIcon(TREE_DEVICE);
             if (!((Device)value).isAlive()) {
                returnValue.setEnabled(false);
          else if (value instanceof GuiPanelGroup) {
             if (expanded) {
                returnValue.setIcon(TREE_PANEL_GROUP_OPEN);
             else {
                returnValue.setIcon(TREE_PANEL_GROUP_CLOSED);
          else if (value instanceof GuiPanel && ((GuiPanel)value).isDirty()) {
             returnValue.setIcon(TREE_PANEL_DIRTY);
          return returnValue;
    }Here is my editor:
    public class WwpJTreeCellEditor extends DefaultTreeCellEditor implements GuiConstants {
          private WwpJTree tree;
           * Creates a new WwpJTreeCellEditor.
           * @param tree The WwpJTree to associate with this editor.
          public WwpJTreeCellEditor(WwpJTree tree) {
             super(tree, (DefaultTreeCellRenderer)tree.getCellRenderer());
             this.tree = tree;
           * Overrides the default isCellEditable so that we check the isEditable() method
           * of the WwpJTreeNodes.
           * @param e An EventObject.
          public boolean isCellEditable(EventObject e) {
             boolean returnValue = super.isCellEditable(e);
             if (returnValue) {
                WwpJTreeNode node = this.tree.getSelectedNode();
                if (node == null || !node.isEditable() || node.isDragging()) {
                   returnValue = false;
             return returnValue;
       }In my JTree I make these calls:
    super.setCellRenderer(new DeviceTreeRenderer());
    super.setCellEditor(new WwpJTreeCellEditor(this));
    super.setEditable(true);

  • Problem with jtree selection

    Hi all,
    I've got a JTree that represents a sort of data that I'm going to change dynamically in my application. I'd like to reset the selection of the user to the leaf she has selected before the change to the tree structure.
    First of all my tree uses DefaultMutableTreeNode to build each node, and each DefaultMutableTreeNode contains a SingleKeyValue object, that is a key-value object (two strings) and that has an hashcode defined as follows:
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         public int hashCode() {
              return this.key.hashCode();
         I hope the hashcode can help me finding the right object even when its value changes (but the key is the same). The construction of the tree is the following:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("The root");
    // iterate and build each node
    SingleKeyValue object = new SingleKeyValue("key","value");
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(object);
    root.add(node);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree  tree = new JTree(model);             
                so the tree is associated to a DefaultTreeModel. Then, when I need to change something in the tree I rebuild the tree and all leafs (with the SingleKeyValues) and rebuild the model:
              TreeModel treeModel = this.myTree.getModel();
              TreeSelectionModel selectionModel = this.myTree.getSelectionModel();
              DefaultTreeModel defaultTreeModel = null;
              DefaultTreeSelectionModel defaultTreeSelectionModel = null;
              TreePath selectedPath = null;
              TreeNode root = null;
              Logger.info("SimpleTreePanel.refreshDatabaseView: treemodel "+treeModel + " selectionModel " + selectionModel);
              if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
                   defaultTreeModel = (DefaultTreeModel) treeModel;
                   root = this.getRoot();
                   // get the selection
                   if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                        defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                        selectedPath = defaultTreeSelectionModel.getSelectionPath();
                        Logger.warn("Selection path of the tree: "+selectedPath);
                   // rebuild the tree
                   defaultTreeModel.setRoot(root);
                   // set the selected element
                   defaultTreeSelectionModel.setSelectionPath(selectedPath);The problem is that after the above code the tree is all closed, no leaf are selected. I guess the problem is with the SingleKeyValueObject because I've tried the default model and it works with, for example, simple strings. Any idea about?
    Thanks,
    Luca

    Here's a complete test program that creates a few SingleKeyValue objetcs (objects with a key and a description) and that then places them into a JTree using the DefaultMutableTreeNode. After that, the selection of user is took and one node is changed, but while the selection is working, the reload/refresh of the tree is not.
    Any idea about how to work on it?
    public class SingleKeyValue extends BaseKeyValue{
          * The key of the database object.
         protected String key = null;
          * The description of this object.
         protected String value = null;
         // constants related to the type of the table this object refers to
         public static final String COMPETENCE = "competenza";
         public static final String FAMILY            = "famiglia_competenza";
         public static final String ROLE              = "ruolo";
         public static final String PROVINCE      = "provincia";
         public static final String KNOWLEDGE  = "titolo_studio";
         public final static String OBJECTIVE      = "obiettivo";
         public final static String PERSON         = "persona";
         public SingleKeyValue( String key, String value, String table){
              super();
              this.key = key;
              this.value = value;
              this.SQLTable = table;
          * @return the key
         public final String getKey() {
              return key;
          * @param key the key to set
         public final void setKey(String key) {
              this.key = key;
          * @return the value
         public final String getValue() {
              return value;
          * @param value the value to set
         public final void setValue(String value) {
              this.value = value;
          * Shows this element.
         public String toString(){
              String ret;
              if( this.showKey ){
                   ret =  this.label + this.key +" { "+ this.value +" }";
              else
                   ret = this.label + this.value;
              // trim the string
              if( ret.length() > this.maxLength )
                   return ret.substring(0 , this.maxLength);
              else
                   return ret;
          * The hash code of this object is the hash code of the key.
          * @return the hash code of the key of the object
         public int hashCode() {
              return this.key.hashCode();
          * Returns true if the object passed is a single key value equals (i.e., with the same key) of this one.
         public boolean equals(Object o){
              if( o== null || (! (o instanceof SingleKeyValue) ) )     return false;
              else
                   return (this.hashCode() == o.hashCode());
         public static void main(String argv[]) throws Exception{
             SingleKeyValue skv1 = new SingleKeyValue("Key1","Description1", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv2 = new SingleKeyValue("Key1a","Description1a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv3 = new SingleKeyValue("Key1b","Description1b", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv4 = new SingleKeyValue("Key2","Description2", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv5 = new SingleKeyValue("Key2a","Description2a", SingleKeyValue.COMPETENCE);
             SingleKeyValue skv6 = new SingleKeyValue("Key2b","Description2b", SingleKeyValue.COMPETENCE);
             DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
             DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(skv1);
             DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(skv2);
             DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(skv3);
             DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(skv4);
             DefaultMutableTreeNode node5 = new DefaultMutableTreeNode(skv5);
             DefaultMutableTreeNode node6 = new DefaultMutableTreeNode(skv6);
             rootNode.add(node1);
             node1.add(node2);
             node1.add(node3);
             rootNode.add(node4);
             node4.add(node5);
             node4.add(node6);
             JTree tree = new JTree(rootNode);
             JFrame f = new JFrame("Tree try");
             f.add( new JScrollPane(tree) );
             f.setSize(300,300);
             f.setVisible(true);
             System.out.println("Please select a node within 10 seconds");
             Thread.sleep(10000);
             // now get the user selection
         TreeModel treeModel = tree.getModel();
         TreeSelectionModel selectionModel = tree.getSelectionModel();
         DefaultTreeModel defaultTreeModel = null;
         DefaultTreeSelectionModel defaultTreeSelectionModel = null;
         TreePath selectedPath = null;
         TreeNode root = null;
         if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
              defaultTreeModel = (DefaultTreeModel) treeModel;
              // get the selection
              if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
                   defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
                   selectedPath = defaultTreeSelectionModel.getSelectionPath();
              // rebuild the tree
              node1.setUserObject(new SingleKeyValue("key20","key changed",SingleKeyValue.FAMILY));
              defaultTreeModel.reload();
              // set the selected element
              defaultTreeSelectionModel.setSelectionPath(selectedPath);
    }

Maybe you are looking for

  • DB polling using custom SQL in SOA Suite 11g

    Hi, We are trying to poll records from a database using custom sql. But all the records in the table are being picked up at the same time and not as per the polling frequency set in the adapter. Below is the configuration from the .jca file: <endpoin

  • Where to see the people code

    Hi, where can I see the people code of a process ? Many thanks before.

  • Reverse the order of elements in an array

    how would i go about Reverse the order of elements in an array??

  • OAAdvancedTableBean navigation problem.

    I have 2 advanced table with 11 rows each. Both have 'records displayed' property of 10. when I click 'previous' link on either table, the data disappears so I invoked appModule.clearAllVOCaches(null, false) on processFormRequest.         } else if (

  • Resizing every page of a large iWeb website

    I've got a website built in iWeb with well over 100 distinct pages, each auto-formatted as 700 pixels wide. I'm now trying to reset every page to 750 pixels.... anybody know of a quick way to reformat every page to the new size, without having to man