URGENT renaming a node in JTree

I have a JTree with nodes created.Say one such node is named ABC
I take in String from a JTextField and use this String to rename the node created.Say this String is ABCXYZ
I use myDefaultMutableTreeNode.setUserObject("ABCXYZ") method to rename.
The problem I face is as ABCXYZ is lengthier than ABC, the node appears like this ABC..... in JTree and when I select the node again ABCXYZ appears fully.
How do I do set this right without deleting the node and adding a new one with ABCXYZ as the name??
Thanks in advance

Thanks both of you. both solutions work. but since an event gets triggered if I select the node I will use DefaultTreeModel.nodeStructureChanged(node) method

Similar Messages

  • Please Help: Renaming a Node In JTree

    Hi All-
    I'm new to Swing, and am having some luck with this, but am running into a little issue that I'm not sure what is causing it... I am renaming a node in my JTree (which is working successfully), however, when the new name is being displayed, it is being displayed with a blue dot on the left side of it (probably indicating it's a node??) -- which I do not want! How can I get rid of this? I would be really appreciative if some experience eyes could look at this and tell me where I'm going wrong...
    Here is my code:
    private void btnRenameIconActionPerformed(java.awt.event.ActionEvent evt) {
    TreePath currentSelection = treeIcons.getSelectionPath();
    if (currentSelection != null){
    //Message box confirming renaming
    int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to rename the" +
    " selected icon or category?", "Rename", JOptionPane.YES_NO_OPTION);
    //If 'YES' -> Allow user to rename the selection
    if(result == JOptionPane.YES_OPTION){
    String newName = (String)JOptionPane.showInputDialog(null, "Input the new name:", "Rename", JOptionPane.PLAIN_MESSAGE);
    DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode)
    (currentSelection.getLastPathComponent());
    MutableTreeNode parent = (MutableTreeNode)(lastNode.getParent());
    if (parent != null){
    final String categoryName = lastNode.toString();
    lastNode.setUserObject(newName);
    DefaultTreeModel model = (DefaultTreeModel)treeIcons.getModel();
    ((DefaultTreeModel)treeIcons.getModel()).nodeChanged(lastNode);
    return;
    //If 'NO' -> -> Return to Icon Manager window
    else{
    return;
    // If there was no selection
    JOptionPane.showMessageDialog(this, "No icon or category was selected!");
    Thanks in advance for your help, it is very much appreciated!!
    -Jeanna

    My apologies for the code tags; first time posting code, but should have previewed it before posting, my bad.
    And, you're correct that you cannot compile, it's a small snipit of our project; I was just hoping that someone would see something in there that looked out-of-whack and know what was wrong.
    However, I've been in that code some more this week and, after feeling rather silly, realized that 'the blue dot' actually denotes that after renaming, the parent node is getting changed to a child node (those have blue dots next to them under the parents.... See, I even hate to admit that). So, my issue is that, when renaming a parent, it is getting changed to a child node.... Can anyone tell me by looking at my code where I'm messing that up?
    Thanks much.
    Swingily challenged yours,
    -Jeanna

  • How to rename node in JTree?(URGENT)

    Hi,all:
    I am facing a renaming problem in JTree. After I rename, the node still remain the old name, Could anybody tell me why and how to solve it?
    The piece of code is as follow:
    JTextField textField = new JTextField();
    newDndTree.setCellEditor(new MyCellEditor(newDndTree,textField));
    newDndTree.setEditable(true);
    class MyCellEditor extends DefaultCellEditor {
    private JTree tree;
    public MyCellEditor(JTree tree, JTextField text) {
    super(text);
    this.tree = tree;
    public boolean isCellEditable(EventObject e) {
    boolean rv = false; // return value
    if(e instanceof MouseEvent) {
    MouseEvent me = (MouseEvent)e;
    if(me.getClickCount() == 3) {
    TreePath path =
    tree.getPathForLocation(me.getX(), me.getY());     
    if(path.getPathCount() == 1) // root node
    return false;
    DefaultMutableTreeNode node =
    (DefaultMutableTreeNode) path.getLastPathComponent();
    Object hitObject=path.getLastPathComponent();
    if(hitObject instanceof TreeNode)
    return (((TreeNode)hitObject).isLeaf());
    return (false);

    Hi,all:
    My problem is it doesn't rename the node, the node remain the old name.
    My piece of code as follow:
    //Set Cell Editor
    newDndTree.setCellEditor(new MyCellEditor());
    //inner class MyCellEditor
    class MyCellEditor extends DefaultCellEditor {   
    public MyCellEditor() {     
    super(new JTextField());
    public boolean isCellEditable(EventObject e) {     
    if(e instanceof MouseEvent) {     
    MouseEvent me = (MouseEvent)e;     
    if(me.getClickCount() == 3) {      
    JTree tree = (JTree)me.getSource();     
    TreePath path = tree.getPathForLocation(me.getX(), me.getY());     
    if(path.getPathCount() == 1) {        
    //System.out.println("Root");     
    return false; // root node     
    DefaultMutableTreeNode node =     
    (DefaultMutableTreeNode) path.getLastPathComponent();     
    Object hitObject=path.getLastPathComponent();     
    if(hitObject instanceof TreeNode) {        
    TreeNode t = (TreeNode)hitObject;     
    boolean b = t.isLeaf();     
    if (b) {          
    //System.out.println("Leaf");     
    return (((TreeNode)hitObject).isLeaf());     
    //else System.out.println("Not Leaf");     
    // System.out.println("Exit");
    return false;
    }

  • Rename custom nodes in a JTree

    Hi all,
    Our problem is that we don't find a way to rename our custom objects that we show in our JTree. We have defined a complete Tree data structure which works fine already ... now we want to be able to rename the nodes in the Tree.
    Our JTree displays concrete instances of our self defined interface INode which has a toString method to display in the Tree. Adding and removing INodes dynamically to the tree works fine already, now we are looking for a way to rename those nodes. Those changes should be noticed finally in the 'name' field of each INode. (INode.setName, INode.getName are present).
    We read from javadoc that a DefaultTreeCellEditor along with an according DefaultTreeCellRenderer are the starting point, but we can't get these 2 integrated to perform correctly. Now the question. Does anyone have an example or an idea of how to write such a CustomTreeCellEditor ??? It is especially important that a possibly provided solution DOES NOT depend on the use of DefaultTreeModel or DefaultMutableTreeNode. Since we use our own Tree Data Structure to be presented in the JTree, we don't have access to possible gimmicks one can expect from the DefaultXXX implementations ...
    Any help very much appreciated!!!

    was able to fix it over here:
    http://forum.java.sun.com/thread.jspa?messageID=4089777

  • Problem inserting new node into JTree with depthFirstEnumeration()

    Hello,
    I'm currently trying to use depthFirstEnumeration() to add and delete nodes for a simple JTree. I've written a method to handle this, but it keeps coming back with an exception saying that 'new child is an ancestor'.
    All I'm trying to do is add and delete nodes from a JTree using add and remove buttons within a swing program. When a user adds the new node the JTree needs to be updated with new labels in sequential order dependent upon a depthFirst traversal of the JTree.
    My current code for the add button is as follows,
    public void actionPerformed(ActionEvent event) 
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
            Enumeration e = rootNode.depthFirstEnumeration();
            if(event.getSource().equals(addButton))
                if (selectedNode != null)
                    while (e.hasMoreElements()) {
                    // add the new node as a child of a selected node at the end
                    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)e.nextElement();
                     // treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    //System.out.print(newNode.getUserObject() + "" + newNodeSuffix++);
                    String label = "Node"+i;
                    treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                    i++;
                      //make the node visible by scrolling to it
                    TreeNode[] totalNodes = treeModel.getPathToRoot(newNode);
                    TreePath path = new TreePath(totalNodes);
                    tree.scrollPathToVisible(path);
                    //System.out.println();
            else if(event.getSource().equals(deleteButton))
                //remove the selected node, except the parent node
                removeSelectedNode();           
        } As you can see in the above code, I've tested the incrementing of the new nodes in a System.out.print() statement and they appear to be incrementing correctly. I just can't see how to correctly output the labels for the nodes.
    Any help and advice always appreciated.

    This is about the 5th posting on the same question. Here is the link to the last posting so you can see what has already been suggested so you don't waste your time making the same suggestion.
    http://forum.java.sun.com/thread.jspa?threadID=704980
    The OP doesn't seem to understand that nodes don't just rename themselves and that renderers will only display the text of the current node. If you want the text displayed to changed, then you need to change the text associated with each node, which means iterating through the entire tree to update each node with new text. Then again, maybe I don't understand the question, but the OP keeps posting the same question without any additional information.

  • Drag and Drop nodes in JTree

    Is there a way to drap and drop JTree nodes without resorting to hacks? http://www.javaworld.com/javatips/jw-javatip97.html outlines a hack to get drag and drop working but it is kinda old. I am wondering whether there is a now a way to do this in Swing. http://weblogs.java.net/blog/shan_man/archive/2006/01/first_class_dra.html outlines a seemingly promising way but when I tried it it still wouldn't let me drag JTree nodes. (btw, if you are going to try it, you must replace TransferHandler.TransferInfo with TransferHandler.TransferSupport. It has apprently been renamed.)

    I have implemented drag and drop of nodes in JTree they same way it is explained in JavaWorld link that you mentioned, I customized it for my application and it worked great.

  • Help needed with finding node in JTree

    Hi,
    In my application i will be entering some string data in a text box for search criteria.
    When I click on search, I will get data from database which will be shown as a JTree.
    This Jtree will have some nodes in which, node with string entered in the search text box exists.
    I need to focus on this node and I have only a string to find this node.
    How can I do this?How can I find a node in JTree using string value?
    Is there any alternate option by which I can achive my need?
    Please suggest.
    Thanks.

    @OP: please assign your dukes.
    @Andre_Uhres: if you don't get rewarded in the next couple of days, please let me know here to get at least one duke for your effort.
    Bye.

  • Renaming of node in Tree UI Element

    Hi All
    I have populated  the Tree Structure as shown below
    A
    A1
    A2
    A3
    B
    B1
      B11     
      B12
      B13     
    B2
    B3
    C
    C1
    C2
      C21
      C22
      C23          
    C3
    C4
    Can you please let me know How to rename of nodes A,A1,B,B1,B11, and C21??
    my requirement is once i select any node either parent or child node or any node then popup opens where current value of a node can be retrieved and user can enter new name where he/she enters new name then that new name could be renamed to the selected node on click of an action.
    If any body helps for sample code on this requirement  then it would be great help to me.
    Thanks
    Kalki Reddy

    In release >= 7.1 I would do that using a context menu. In earlier releases you could use a static menu at the TreeNodeType or TreeItemType. But I would not open the renaming dialog on selection of a tree node.
    How to do that with a static menu?
    - Add menus to the TreeNodeType/TreeItemType instances of your tree.
    - Create an action "RenameTreeNode" with a parameter "treeNodeContextElement" of type IWDNodeElement.
    - Add MenuActionItem to the menu, assign above action and define event parameter mapping "nodeElement" -> "treeNodeContextElement"
    Then you will know the context element that represents the tree node where the menu is opened in the action handler of the menu item. In the action handler, open a popup window with an input field to enter the new name for the tree node. Use context mapping to pass the inout field value to the view controller that opens the popup. In the close action of the dialog, assign the edited value to the context element representing the tree node.
    Armin

  • Wordwrap nodes in jtree

    Anyone know how we can do wordwrap of nodes in jtree?
    Please help...
    Thanks.

    Any example on this? what html code should I use? The simplest possible, eg
    yourNode.setText("<html>" + yourNodeText + "</html>");Most JComponents can render this html string and produce a good result. But if you wanna get a little more complex and use styles and other web things, then do as said, (two posts above) and use a JEditorPane specifically for cell renderer
    ICE

  • How to set the default tree node in JTree?

    I want to set a default tree node in JTree when start the program,
    what is the method or the function to call?
    Thanks~

    If you by "default" mean "selected", then you can use one of the setSelectionXXX methods in the JTree API.
    If you by "default" mean something else, never mind this post :-)

  • Setting custom color for selected node in JTree?

    Hi,
    i want to set my own color for selected node in JTree. i don't want to set for all the nodes...how to set Color for Selected node using TreeCellRender class?
    Thanks
    Mani

    I assume you are not setting a custom tree cell renderer...
    javax.swing.JTree theTree = ...;
    java.awt.Color newBGColor = ...;
    ((javax.swing.tree.DefaultTreeCellRenderer)theTree.getCellRenderer())
        .setBackgroundSelectionColor(newColor);

  • Add node to JTree

    I have an already populated JTree. At Runtime I add one or more node to JTree, using something like
    parentNode.add(newNode)....
    If I call a repaint method, the new node isn't visible, I have to reload model using
    DefaultTreeModel dtm = ((DefaultTreeModel)myTree.getModel());
    TreeNode rootNode = (TreeNode) dtm.getRoot();
    dtm.reload(rootNode);
    Unfortunately this method cause the lost of focus on the currently selected node and the collapse of all JTree around its root node; If I change an existing node (for example changing its text or icon) I must reload the model too!!!
    Does exist an other more "soft" method to change the aspect of a JTree without reload the entire model?

    You must use or implement the
        public void valueForPathChanged(javax.swing.tree.TreePath path,java.lang.Object newNode) {
            Object[]    p = path.getPath();
            Object[]    pp = p;
            //insert node here
            int[] ci = new int[] {index};
            Object[] cc = new Object[] {node};
            fireTreeNodesChanged(this, pp, ci, cc);
            fireTreeStructureChanged(this, pp, ci, cc);
        }from the TreeModel. To fire the last two is essensial.
    I implemented a GP in JAVA so i had the same problem wehn i started.

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

  • How to reach at a node of JTree : Urgent

    Hay all,
    Plz tell me that how to reach at a particular node in a JTree, whose name is known to you.I have used a DefaultTreeModel to create a tree. As
    deviceTreeModel=new DefaultTreeModel(rootNode);
    tree = new JTree( deviceTreeModel );
    Thanks and Regards,
    Sharad Agarwal

    an inefficient way is to traverse the tree to find the node
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeModel.getRoot();
    public TreeNode getNode(DefaultMutuableTreeNode node, String nodeName){
        if (node.getChildCount() == )
            return null;
         for (Enumeration e = node.childrens() ; e.hasMoreElements() ;) {
             DefaultMutuableTreeNode child = (DefaultMutuanbleTreeNode) e.nextElement();
             if (child.getUserObject.().toString().equals(nodename))
                 return child;
             else
                 getNode(child, nodeName);
    }once you got the node, you can use the
    DefaultTreeModel.insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index)

  • How to dynamically add Nodes to JTree?

    How to add nodes to a Jtree by getting the information into a specific file
    For example, in JList:
    DefaultListModel workgroups;
    workgroups = new DefaultListModel();
    List<String> workgroupsList = new ArrayList<String>();
    workgroupsList = ParserUtils.getWorkgroupList(ParserUtils.getConfigPath() + "\\.workgroup.properties");
    if (!workgroupsList.isEmpty()){
         for (String workgroup : workgroupsList){
              workgroups.addElement(workgroup.toString().trim());
    workgroupList = new JList(workgroups); //adds the list workgroupsThe output of this will be a JList displaying the list of workgroups per line. The list could be found in a file name "workgroup.properties"
    Question is, is it possible to adapt this same method in JTree. The information per line will serve as one node in the tree. For example, I have 3 workgroups in the list, there will also be 3 nodes to be found in the tree.
    Any suggestions?
    THanks.

    There's a huge JTree example in the Swing tutorial. It's a bit of a beast to use.

Maybe you are looking for