RemoveNode in JTree

Hello,
I'm currently working on a DialogBox where the user can remove some children from a JTree.
By clicking on a "Delete" Button, the currently hilited leaf is just removed using:
TreePath currentSelection = tree.getSelectionPath();
if (currentSelection != null)
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)(currentSelection.getLastPathComponent());
MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
if (parent != null)
treeModel.removeNodeFromParent(currentNode);
return;
The problem is when removing the last leaf of a node; the empty node becomes automatically a leaf of the root node; I rather would like it to remain an empty node....
Hoping it's clear enough, Thanks for your help
Loic

If I remember correctly, the DefaultMutableTreeNode returns true if it has no children. By returning true the tree cell renderer will draw the node as a leaf, if it returns false it will render it as a folder node.

Similar Messages

  • How to Remove a Node from JTree?

    I want to remove a node from a JTree but the node may or maynot be visible.
    My method takes a String which is the name of the node.
    The nodes im using are DefaultMutableTreeNode
    This is my code so far but it doesnt work.
    public void removePerson(String pName)
              TreePath node = tree.getNextMatch(pName,0,Position.Bias.Forward);
              tree.expandPath(node);
              tree.removeSelectionPath(node);
    }Any Suggestions or ways which i could achive this?
    Thank you,

    I don't think removeSelectionPath is what you want to use.
    These should help:
    [http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)|http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html#removeNodeFromParent(javax.swing.tree.MutableTreeNode)]
    [http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml|http://www.roseindia.net/java/example/java/swing/RemoveNodes.shtml]

  • How remove (or change) children inside a JTree

    hi,
    I did a program where there are informations with a structure of dependence that should be showed inside JTree components.
    I realized this purpose in my program .
    But I am findind very difficult (after having put the information inside the JTre in the start) to show them again inside the JTrees when they are changed.
    I don't know how to remove or change the informations after they are put on the children of the JTree using the methods that I found in the documentation to reach this purpose...
    I need some help ...
    To explain well my problem, and facilitate the helpers, I post some code that show my problem..
    The program show a GUI with some JTrees.
    The informations are contained in two strings, and in the GUI are also two buttons that can load the informations inside the JTree when they are clicked.
    Thank you in advance
    regards
    tonyMrsangelo
    public class JTree_TryToUseIt_ChangingNodes extends javax.swing.JFrame {
        private PanelFulViewConteiner jPanelFulViewConteiner;
        Dimension dimPrefArcPanels = new Dimension(910, 150);
        Dimension dimMinArcPanels = new Dimension(700, 100);
        Dimension dimPrefSemiArcPanels = new Dimension(850, 140);
        Dimension dimMinSemiArcPanels = new Dimension(550, 90);
        Dimension dimPrefBodyXpicPanels = new Dimension(900, 150);
        Dimension dimMinBodyXpicPanels = new Dimension(700, 150);
        Dimension treePrefDim = new Dimension(90, 110); //
        Dimension treeMinDim = new Dimension(60, 110);
        PanelToShowTrees panel_trees;
        public JTree_TryToUseIt_ChangingNodes() {
            getContentPane().setLayout(new GridBagLayout());
            GridBagConstraints gBC = new GridBagConstraints();
            jPanelFulViewConteiner = new PanelFulViewConteiner();
            gBC.gridx = 0;
            gBC.gridy = 0;
            gBC.gridwidth = 10;
            add(jPanelFulViewConteiner, new GridBagConstraints());
            gBC.gridx = 0;
            gBC.gridy = 1;
            gBC.gridwidth = 10;
            pack();
            panel_trees = this.jPanelFulViewConteiner.jPanelFulContainerTop.panelToShowTrees;
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocation(50, 50);
            setVisible(true);
        private void fillTrees(String[] strings) {
            collapseTrees();
            removeNodes();
            for (int index = 0; index < strings.length; index++) {
                DefaultMutableTreeNode dmt = new DefaultMutableTreeNode(strings[index]);
                String knotStr = strings[index].substring(0, 1);
                int knot = -1;
                try {
                    knot = Integer.parseInt(knotStr);
                } catch (NumberFormatException e) {
                panel_trees.root_Node[knot].add(dmt);
                panel_trees.validate();
                panel_trees.repaint();
            collapseTrees();
        void collapseTrees() {
            for (int i = 0; i < 8; i++) {
                panel_trees.jTree.collapseRow(0);
    panel_trees.jTree[i].expandRow(0);
    panel_trees.validate();
    panel_trees.repaint();
    void removeNodes() {
    for (int i = 0; i < 8; i++) {
    panel_trees.jTree[i].removeAll();
    panel_trees.validate();
    panel_trees.repaint();
    public static void main(String args[]) {
    JTree_TryToUseIt_ChangingNodes xx = new JTree_TryToUseIt_ChangingNodes();
    class PanelFulViewConteiner extends JPanel {
    PanelFulContainerTop jPanelFulContainerTop;
    PanelFulContainerBottom jPanelFulContainerBottom;
    public PanelFulViewConteiner() {
    GridBagLayout gbl = new GridBagLayout();
    this.setLayout(gbl);
    GridBagConstraints gBC = new GridBagConstraints();
    jPanelFulContainerTop = new PanelFulContainerTop();
    gBC.gridx = 0;
    gBC.gridy = 0;
    add(jPanelFulContainerTop, gBC);
    jPanelFulContainerBottom = new PanelFulContainerBottom();
    gBC.gridx = 0;
    gBC.gridy = 2;
    add(jPanelFulContainerBottom, gBC);
    class PanelFulContainerTop extends JPanel {
    PanelToShowTrees panelToShowTrees;
    public PanelFulContainerTop() { // costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    setLayout(new FlowLayout());
    panelToShowTrees = new PanelToShowTrees();
    add(panelToShowTrees);
    }// costruttore
    class PanelFulContainerBottom extends JPanel {
    JButton but1 = new JButton("load string1");
    JButton but2 = new JButton("load string2");
    String[] str1 = {"0-AAA", "0-BBBBBB", "2-CCCCC", "2-DDDDDD", "2-EEEEEEE", "5-FFFFFF", "5-GGGGGG", "5-HHHHHH", "7-IIIIII", "7-KKKKKKK", "7-LLLLLL", "7-MMMMMM"};
    String[] str2 = {"0-aaaaa", "0-bbbbb", "0-cccc", "2-ddddd", "2-eeee", "3-ffffff", "3-gggggg", "3-hhhhh", "4-iiiiii", "4-kkkkk", "7-lllllll", "7-mmmmm", "7-nnnnn"};
    public PanelFulContainerBottom() {// costruttore
    this.setMinimumSize(dimMinArcPanels);
    this.setPreferredSize(dimPrefArcPanels);
    add(but1);
    but1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str1);
    add(but2);
    but2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fillTrees(str2);
    class PanelToShowTrees extends JPanel {
    JScrollPane jScrollPane[];
    JTree jTree[];
    DefaultMutableTreeNode[] root_Node;
    public PanelToShowTrees() {
    this.setMinimumSize(dimMinSemiArcPanels);
    this.setPreferredSize(dimPrefSemiArcPanels);
    setLayout(new FlowLayout());
    jScrollPane = new JScrollPane[8];
    jTree = new JTree[8];
    root_Node = new DefaultMutableTreeNode[8];
    for (int i = 0; i < 8; i++) {
    root_Node[i] = new DefaultMutableTreeNode(" " + (8 - i));
    jTree[i] = new JTree(root_Node[i]);
    jScrollPane[i] = new JScrollPane();
    jScrollPane[i].setViewportView(jTree[i]);
    add(jScrollPane[i]);
    jScrollPane[i].setPreferredSize(treePrefDim);
    jScrollPane[i].setMinimumSize(treeMinDim);
    jTree[i].addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
    showContentOfTheTree(e);
    private void showContentOfTheTree(TreeSelectionEvent e) {
    String stringaGotFromEvent = e.getPath().toString();
    JOptionPane.showMessageDialog(rootPane, "found =---> " + stringaGotFromEvent);

    hi Andre,
    thank you for answering me.
    I have not much practice with JTrees so I find some difficulty to use it...
    After I got your advice, I made changed a little the design of my program..
    This it is a program for management of a dentist office, and I would show in 8 JTrees (every jTree root represents the teeth in a dental arch) the treatments that each tooth got.
    How I said, the 8 JTree roots are representing the teeth, and in this architecture the problem is:
    - to add a node to a tree root to indicate a treatment for that tooth;
    - to delete all the children from a jTree root before beginning to add new child, before writing again treatments, when the informations are changed.
    Following your help, I made this two functions to reach this purpose:
    private void assingTreatmentToTooth(int toothNmbr, String strTreatment) {
            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(strTreatment); // new treatment to add
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel(); // get model for the root Tree
            DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model.getRoot();
            model.insertNodeInto(newChild, parentNode, 0); // always assign 0 as first node
        } // assingTreatmentToTooth()
    private void removeTreatmentFromAtooth(int toothNmbr, int childNmbr) {
            DefaultTreeModel model = (DefaultTreeModel) panel_trees.jTreeXdentalRoots[toothNmbr].getModel();  // get model for the root Tree
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
            model.removeNodeFromParent(child);
        } // removeTreatmentToTooth()when the second function is executed, I get this error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.tree.DefaultTreeModel cannot be cast to javax.swing.tree.TreeNode
    at the line : DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(model, childNmbr);
    could you tell me what is wrong ?
    regards
    TonyMrsangelo

  • Swing JTree class problems... (feature request)...

    Hello,
    I'd like to be able to change Nodes positions (at least two children inside the same parent node without having to remove/add them [which looses expanded/selected states]).
    With regards,
    Pavel Krupets

    hi.,
    use this. This will add new node with out collapsing the tree.
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener (new MyTreeModelListener);
            jTree1.setModel(treeModel);
        jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    jScrollPane1.setViewPortView(jTree1);
    private void addNode(String node)   // To add node.
            DefaultMutableTreeNode = parent;
            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(node); // newNode is the one which your need to insert in the JTree.
             parent = jTree1.getLastSelectedPathComponent(); // LAST SELECTED NODE.
             treeModel.insertNodeInto(newNode,parent,parent.getChildCount());
    private void removeNode()   // To Remove selected node from tree.
       TreePath lastPath = jTree1.getSelectionPath();
        DefaultMutableTreeNode selectedNode = jTree1.getLastSelectedPathComponent();
        treeModel.removeNodeFromParent(selectedNode);
    }

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

Maybe you are looking for

  • I'm getting an error message: Could not complete your request because of a program error.

    I get the error message when I try and print. I do custom printing for clients. I've tried turning off my computer and re-starting it, but that didn't help. Do I need to un-install CS5, and then re-install?

  • Can I to use a remote agent in CCX??

    Hi, I have a site A (Brazil) with CUCM and CCX working... But, I need to create another queue with a new agent that will stay at Chile (Site B)... Can I to register the new agent at Brazil CUCM? Can I to create a new queue at Brazil CCX for him? What

  • Selectmanyshuttle does anyone have information about it

    Hi all i have been searching for information about the component selectmanyshuttle and i can't really find anything that i find relevant to help me on this(i never used select many components). actually information on any component that are selectman

  • Script Versioning InDesign CS5 (INX-Export)

    Dear all, I am currently encountering a problem with Script Versioning or -- perhaps I don't understand the purpose of Script Versioning... In CS4 I wrote a Visual Basic Script (see below) that exports INX of the current document to disk. Since CS5 n

  • Sca component wsa:Address different to SOAP Action

    Hi, i have developed an SCA component with SOA Suite 11.1.1.2 and JDeveloper 11.1.1.2. I have an outgoing service call behind a mediator. the soa suite sends a request to this service containing WS-Addressing information. These WS-Addressing informat