StartEditingAtPath()  in jtree

I'm creating an explorer-ish component. When the user changes the value of the node I pop up an alert if the value is equal to that of its sibling nodes and call StartEditingAtPath() to keep
the user there.
After typing in the value if the user presses Enter Key
the user stays there in textfield if the value already exists.
Problem is - if the user clicks on another node
the focus moves leaving the current node with its
existing value. How do I prevent the user from selecting
another node whilst editing the current one?
cheers

Not sure, but I think when you assign a listener to your tree model, the method:
public void treeNodesChanged(TreeModelEvent e)
should catch every change of the node (thus, also change of the name)

Similar Messages

  • Editing in JTree...

    hi All,
    1) In all JTree component,there is default editor.
    If you click a node,then again if you click that node,
    some editor is coming by default ,which is holding the whole text of the selectednode.I want to highlight all the characters in that editor.Is it possible?
    2) Similarly In some situation,under particular parent I don't want to allow such type of default editor to edit for all the children.Is it possible?
    3)Like windows Explorer feature,I want to set the tooltip box for the node which is hidden partly in the JTree
    Is it possible?
    If any suggestions,it will be appreciated.
    Advanced thanks

    Hi
    1) overwrite starteditingatpath from JTree, call method of superclass and request focus for editing component afterwards. You can also add some code to the cellEditor (waiting and selecting).
    2) extend your cell editor, check node and allow editing only if possible
    3) you can set a tooltip for each node. getToolTipText(MouseEvent) of the JTree asks the different values from the cell renderer (bad performance as everytime called, tooltip should be shown). overwrite method, ask if node is fully visible and return the tooltip of the node only in this case
    Hope this helps

  • Jtree startEditingAtPath cannot work

    I want my JTree to be always automatically goes into editing mode everytime a node is selected. I have add a treeselectionlistener that will initiate startEditingAtPath everytime the tree selection changed. However, the celleditor just won't show.
    Here is my code:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.util.LinkedList;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class MyTreePane extends JScrollPane implements TreeSelectionListener{
         private JTree tree;
         private DefaultTreeModel treeModel;
         private DefaultMutableTreeNode rootNode;
        public MyTreePane() {
            super();
            setPreferredSize(new Dimension(950,330));
            setMinimumSize(new Dimension(950,330));
            setSize(new Dimension(950,330));
            revalidate();
            rootNode = new DefaultMutableTreeNode("Root");
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            tree.setBackground(Color.lightGray);
            MyCellRenderer renderer = new MyCellRenderer();
             tree.setCellRenderer(renderer);
             tree.setCellEditor(new MyCellEditor(tree,renderer));
            tree.setEditable(true);
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
            tree.setRootVisible(false);
              tree.setDragEnabled(false);
              setViewportView(tree);
              DefaultMutableTreeNode firstNode = new DefaultMutableTreeNode("Good");
              treeModel.insertNodeInto(firstNode, rootNode, 0);
              tree.scrollPathToVisible(new TreePath(firstNode.getPath()));
              tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              tree.addTreeSelectionListener(this);
              tree.setSelectionPath(new TreePath(firstNode.getPath()));
        public void insertNewRowAfter(int index){
              DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();
              treeModel.insertNodeInto(newNode, rootNode, index+1);
              tree.scrollPathToVisible(new TreePath(newNode.getPath()));
              tree.setSelectionPath(new TreePath(newNode.getPath()));
        //listener to selection change event
        public void valueChanged(TreeSelectionEvent e){
             DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                  tree.getLastSelectedPathComponent();
             if (node == null)
                  return;
             tree.startEditingAtPath(new TreePath(node.getPath()));
    class MyCellRenderer extends DefaultTreeCellRenderer{
         public Component getTreeCellRendererComponent(JTree tree, Object value,
                   boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){
                // Get background color based on selected state
              JLabel renderer =(JLabel) super.getTreeCellRendererComponent(tree,
                        value,selected,expanded,leaf,row,hasFocus);
              Color background = (selected ? Color.yellow : Color.white);
              renderer.setOpaque(true);
              renderer.setBackground(background);
             renderer.setMinimumSize(new Dimension(950,(int)renderer.getMinimumSize().getHeight()));
             renderer.setPreferredSize(new Dimension(950,(int)renderer.getPreferredSize().getHeight()));
              renderer.setText(value.toString());
             return renderer;
    class MyCellEditor extends DefaultTreeCellEditor{
         public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer){
              super(tree,renderer);
         public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor){
              super(tree,renderer,editor);
         public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected,
                   boolean expanded, boolean leaf, int row){
              Component c = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
              Component editor = realEditor.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
              SwingUtilities.updateComponentTreeUI(c);
              if (editor instanceof JTextField)
                   //widen the textfield for the editor
                   ((JTextField)editor).setColumns(85);
                   ((JTextField)editor).setText(value.toString());
                   //((JTextField)test).selectAll();
              return c;
       

    Use path from the event.
    public void valueChanged(TreeSelectionEvent e){
             tree.startEditingAtPath(e.getPath());
    }Regards,
    Stas

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

  • JTree node duplication

    I have a JTree which checks for duplication everytime a child node gets added.I have a combobox in cell Editor from which user can select the child node or he can give his own name also.If the node is already added,it will give a warning dialog.I have set root node as 'Device'.If i add 'Device' again in the tree somewhere,the warning dialog pops up two times.I want the warning dialog to come only one time.For other names it comes only once.I use arraylist to store the names of the nodes already added in tree and compare the new node(to be added)with them.i have given the code here..
    public void readTreeNodeNames(DefaultMutableTreeNode node) {
         treeNodeNames.add(node.toString().toLowerCase());
         for(Enumeration en=node.children();en.hasMoreElements();) {
         DefaultMutableTreeNode childNode=(DefaultMutableTreeNode)en.nextElement();      
         treeNodeNames.add(childNode.toString().toLowerCase());
         if(!childNode.isLeaf()) {
         readTreeNodeNames(childNode);
    public void treeNodesChanged(TreeModelEvent tme){
         selectedNode = (DefaultMutableTreeNode)hierarchyTree.getLastSelectedPathComponent();
         if(treeNodeNames.contains(selectedNode.toString().toLowerCase())) {                   
         Toolkit.getDefaultToolkit().beep();
         JOptionPane.showMessageDialog(this,BuilderUtils.getString("DDFE.DeviceHierarchyScreen.warningMessage5.text"),"Warning!",JOptionPane.WARNING_MESSAGE);     
         setEditable();     
    public void setEditable(){
         treeNodeNames=new ArrayList();
         readTreeNodeNames((DefaultMutableTreeNode)dtm.getRoot());     
         TreePath treePath=(TreePath)hierarchyTree.getSelectionPath();
         hierarchyTree.expandPath(hierarchyTree.getSelectionPath());
         hierarchyTree.setEditable(true);
         hierarchyTree.startEditingAtPath(treePath);
         updateUI();
    public void createNode(){
         // code for creating a Node at same level
         selectedNode=(DefaultMutableTreeNode)hierarchyTree.getLastSelectedPathComponent();
         parentNode=(DefaultMutableTreeNode)selectedNode.getParent();           
         DefaultMutableTreeNode node=new DefaultMutableTreeNode("");
         rootNode=(DefaultMutableTreeNode)node.getRoot();     
         dtm.insertNodeInto(node, parentNode, parentNode.getChildCount());           
         TreePath tp = new TreePath(node.getPath());
         hierarchyTree.scrollPathToVisible(tp);
         hierarchyTree.setSelectionPath(tp);      
         setEditable();

    What you can do is to create a second TreeNode with same userOject as in first.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • JTREE request edit mode for one node

    hello,
    my jtree is editable
    tree.setEditable(true); // double click on a node and it goes in "edit mode"
    I would like to set a specific node into "edit mode" (just like when you create a new folder in windows - new folder appears in edit mode - you just have to type the name of the folder)
    //set the node selected
    setSelectionPath(new TreePath(newfolder.getPath()));
    // set the node in edit mode - does not exist ???
    setEdit((new TreePath(newfolder.getPath())); ????
    Second question:
    how can I avoid a specific node from being editable ?
    // set all the nodes editable !!
    tree.setEditable(true);
    thanks a lot !

    polo777 wrote:
    I would like to set a specific node into "edit mode" (just like when you create a new folder in windows - new folder appears in edit mode - you just have to type the name of the folder)[JTree.startEditingAtPath|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTree.html#startEditingAtPath(javax.swing.tree.TreePath)].
    how can I avoid a specific node from being editable ?Override [JTree.isPathEditable|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTree.html#isPathEditable(javax.swing.tree.TreePath)].

  • Triggering a CellEditor at will in a JTree

    Hi,
    I have following problem:
    My application contains a JTree view of Directories containig audio signal references. After starting the application for the first time(one default directory (node) is always created when app is first started ) and after creating a new directory I want the node text to be directly editable. Is to say I want the cell editor to be triggered just like after pressing default key F2 or clicking once on to the node through the application itself. If possible the text (box) content should be highlighted from the beginning so that all the user has to do is enter his new directory name. This procedure is similar to creating a new directory using the windows file explorer. I understand one can acces routines of the trees CellRenderer but havent found a means to solve my problem yet.
    Any ideas anyone? Any help welcome.
    Greets,
    the lawoguy

    Hi joop
    Did you try:
    JTree tree;
    TreePath path;
    tree.startEditingAtPath(path);
    Good Idea! Unfortunately only the editing is started that is the text box appears.
    Neither is a cursor set or the text highlighted.
    Is there any mechanism to achieve this from here?
    Greets,
    the lawoguy

  • Pls help with JTree editor problem

    Hi,
    I have a JTree where each node in the tree is a JPanel. In each
    JPanel are two JTextField objects. Only one of the JTextField objects
    is editable.
    When I click on node (a line in the JTree) with the mouse, it is
    painted using the custom editor (TreeCellEditor) that I have written.
    When the selected and editable JTextField has the focus, and when a
    certain key is hit, I capture that key, do some things, and then select
    a different node in the JTree.
    When selecting the new node, I need the node to be painted with
    the editor, just as if I had clicked on it with the mouse.
    In the method called as a result of the key binding, I call the
    following --
    TreeUI.stopEditing( JTree ) -- stops editing of the cell that resulted
    in the key binding call
    TreeUI.startEditingAtPath( JTree, TreePath )
    -- according to the JavaDocs, this should select the new cell and
    start editting of it.
    This last method does call my editor to get the components, but then my
    Renderer is also called (twice in fact). When the cell is painted, it is
    painted with the Renderer's components.
    PLEASE HELP HERE !

    Thank you so much for giving a reply to this problem.
    I will experiment with your suggestion. However, in looking at the JavaDocs
    I would need to make one class that implements both TreeCellEditor and
    TreeCellRenderer, with the methods getTreeCellEditorComponent() and getTreeCellRendererComponent(). Since currently, my editor is called and then
    my renderer is called, over-writing the editor's result, I would suspect that
    both of these methods would also be called (even though they are in the same
    class), having the same effect.
    Again, thank you.

  • I have a problem with creating a node in the JTree

    Hello All!
    I have a problem when I try to create a new node in the JTree. If the parent node of the new node has any other children, I get following NullPointerException exception :
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTreeUI.startEditing(BasicTreeUI.java:1959)
         at javax.swing.plaf.basic.BasicTreeUI.startEditingAtPath(BasicTreeUI.java:506)
         at javax.swing.JTree.startEditingAtPath(JTree.java:1921)
         at ru.sirena2000.jxt.iface.action.TreeActionHandler.createNode(TreeActionHandler.java:62)
    It seems to me, that path of creating node was not defined in the BasicTreeUI.
    Note, if the parent node has no other children, the new node will be successfully created. How can I solve this problem? Help me, please!
    I use java version 1.4.2-b28

    Sorry, I forgot to show a piece of code, where I try to create a new node. This piece of code see above. "tree.scrollPathToVisible(path);" is a string, which throws an exception.
    tree.repaint();
    TreePath path = tree.getSelectionPath();
    if (path == null) {
    return;
    if (tree.isCollapsed(path)) {
    tree.expandPath(path);
    DefaultMutableTreeNode parentNode =
    (DefaultMutableTreeNode)path.getLastPathComponent();
    IconData childData = defineIconData(parentNode);
    IconData newData = childData.copy();
    newData.getNodeObject().clearNodeObj();
    newData.getNodeObject().setNodeText("New");
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newData);
    editingData = newData;
    editingData.getNodeObject().setStatus(TreeNodeData.NEW_STATUS);
    parentNode.add(newNode);
    DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
    path = path.pathByAddingChild(newNode);
    tree.scrollPathToVisible(path);
    tree.startEditingAtPath(path);
    saveChangesInBuffer(newNode, TreeNodeData.NEW_STATUS);
    model.nodeStructureChanged(parentNode);

  • JTree - focusing userObjects (JComponents)

    Hi everyone!
    I have the following problem and i am despairing:
    my JTree has DefaultMutableTreeNodes. Every userObject of a node is a JPanel with a JLabel and a JComponent (normally JTextFields or JComboBoxes).
    Now I want to put the focus on the JComponent !!!
    it works, by clicking on the JComponent, but not if i go through the tree with the cursor-keys (although the selection is changed to the nodes!)
    requestFocusInWindow() does not work, because isDisplayable() of the JComponent returns false!
    PEASE HELP !!!
    Thanks for any suggestions !

    Hi Denis !
    I think I haven't configured the editor in the right way !?! Here's more information:
    I have a cellRenderer, a cellEditor and a selectionListener.
    From the selectionListener I call the startEditing Method:
    public void valueChanged(TreeSelectionEvent e) {
          TreePath tp = e.getNewLeadSelectionPath();
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
          if (node == null)
            return;
          if (MyTreeCellEditor.isCellEditable(node))
         theTree.startEditingAtPath(tp);
    }startEditingAtPath throws a NullPointerException if I click on a Node
    at javax.swing.plaf.basic.BasicLookAndFeel.compositeRequestFocus(BasicLookAndFeel.java:1748)
    and going through the tree with the cursor-keys doesn't work at all !!?!?!?
    the cellEditor Method:
    public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected,
                                                boolean expanded, boolean leaf, int row) {
          DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
          Object userObject = node.getUserObject();
          if (userObject instanceof MyPanel)
            return (MyPanel) userObject;
           // else:
          return super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
    }Thanks for help !
    Andreas

  • JTree editing difficulties

    I am having trouble with the editor on the JTree. I am trying to make it possible for the user to right click on an element of the Tree, have a pop-up menu come up with an option "Rename", have the user edit the name, and then have the name changed. It is almost working as described. The difficulty is that when the user has finished editing, the name is changed properly, but the displayed name is clipped in the wrong place.
    More particularly, what happens is as follows:
    1. The user right-clicks on an existing leaf
    2. The pop-up menu comes up with the rename option
    3. The icon disappears and the user sees a box to type the changes into, as per spec
    4. The user makes his/her change
    5. The name is changed properly, but the display acts as though it were clipped at the point where the right side of the text would have been, had the icon not been there. It is as though the right side of the display does not move, but the left side does, for some reason.
    Any ideas of what is going wrong/workarounds?

    I'm afraid that doesn't work. I both revalidate and then repaint, but it still acts the same.
    Perhaps I should make one point clear: The user can always edit the tree by double-clicking on the leaf. That works fine. It's just the editing induced directly in my personal code that has trouble.
    The code is essentially as follows:
    To add the rename item to the pop-up menu:
    renameItem.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                    TreePath toEditPath = theEnvelope.getTreePathTo( selectedObject );
                    jTree1.startEditingAtPath( toEditPath );
            } );The tree has the following listener on it:
    CellEditorListener newTreeCellListener = new CellEditorListener() {
                public void editingCanceled( ChangeEvent e) {
                public void editingStopped( ChangeEvent e ) {
                    Object newVal = ((DefaultCellEditor)e.getSource()).getCellEditorValue();
                    Object oldVal = ((EquationTreeCellEditor)e.getSource()).getEditedEquationManager();
                    //Make sure it changes the name only if the name has actually been changed, not
                    //just edited
                    if ( oldVal instanceof EquationManager ) oldVal = ((EquationManager)oldVal).getName();
                    if ( !oldVal.equals( newVal.toString() ) ) {
                        renameEquationManager( oldVal, newVal );
            } ;However, this listener is invoked both when the editing was initiated with the popup menu and when the user double-clicked. The regular double-clicking method works while the right-clicking one does not.

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

  • 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 :(

Maybe you are looking for