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

Similar Messages

  • 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 select node in JTree without firing event?

    I have got standard situation. JTree in the left panel, and several edit boxes in right panel. Certainly, I have TreeSelectionListener, which on every tree node selection shows corresponding model values in edit boxes.
    I'd like to implement next logic:
    1. Something was changed in any edit box in right panel. Model has been changed.
    2. User clicks on different node in tree.
    3. Dialog "Message was not saved. Save?" with Yes/No/Cancel buttons are shown.
    Yes/No buttons are easy to handle.
    Question is about Cancel. I'd like on Cancel button left all edit boxes in their present state (do not restore values from saved model) and select back node, which wasn't saved.
    Problem is next. If I select node by setSelectionPath or smth like that, but... JTree fires event and my listener receives onTreeItemSelected back, which checks that node wasn't saved and ......
    Who does have any idea, or have done similar tasks? How can I select node and do not allow tree fire event this time?
    Thanks in advance.

    First, as soon as the model changes (when editing any
    combo box) some flag will be set. Now the logic which
    updates the combo boxes will do it only on a change of
    the current node and (this is new) if the flag wasn't
    set. You should have some flag anyway because somehow
    you must determine when to show the dialog, shouldn't
    you?Yes, I have got this logic implemented. But it's only the half :)
    I know exactly when my model has been changed, but if it was changed, i'd like to ask user what to do next - svae/loose changes/cancel
    And on cancel i'd like to select last edited tree node and do not get event from tree at that moment.
    >
    Second way, prevent selecting a new node if that flag
    has been set. You could do this by subclassing
    DefaultTreeSelectionModel and overriding some methods
    (setSelectionPath() et al).Ok. I'll investigate this.
    >
    MichaelThanks.

  • How to highlight node in JTree?

    After the tree has been displayed, I want to highlight the nodes matching some certain keywords. How to implement that? Nothing useful is found in past threads.
    thanks.

    to take a wild guess:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class HighlightTreeNodeTest {
      private final JTree tree       = new JTree();
      private final JTextField field = new JTextField("foo");
      private final JButton button   = new JButton();
      private final MyTreeCellRenderer renderer =
        new MyTreeCellRenderer(tree.getCellRenderer());
      public JComponent makeUI() {
        field.getDocument().addDocumentListener(new DocumentListener() {
          @Override public void insertUpdate(DocumentEvent e) {
            fireDocumentChangeEvent();
          @Override public void removeUpdate(DocumentEvent e) {
            fireDocumentChangeEvent();
          @Override public void changedUpdate(DocumentEvent e) {}
        tree.setCellRenderer(renderer);
        renderer.q = field.getText();
        fireDocumentChangeEvent();
        JPanel p = new JPanel(new BorderLayout(5, 5));
        p.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        p.add(field, BorderLayout.NORTH);
        p.add(new JScrollPane(tree));
        return p;
      private void fireDocumentChangeEvent() {
        String q = field.getText();
        renderer.q = q;
        TreePath root = tree.getPathForRow(0);
        collapseAll(tree, root);
        if (!q.isEmpty()) searchTree(tree, root, q);
        tree.repaint();
      private static void searchTree(JTree tree, TreePath path, String q) {
        TreeNode node = (TreeNode)path.getLastPathComponent();
        if (node==null) return;
        if (node.toString().startsWith(q)) tree.expandPath(path.getParentPath());
        if (!node.isLeaf() && node.getChildCount()>=0) {
          Enumeration e = node.children();
          while (e.hasMoreElements())
            searchTree(tree, path.pathByAddingChild(e.nextElement()), q);
      private static void collapseAll(JTree tree, TreePath parent) {
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        if (!node.isLeaf() && node.getChildCount()>=0) {
          Enumeration e = node.children();
          while (e.hasMoreElements()) {
            TreeNode n = (TreeNode)e.nextElement();
            TreePath path = parent.pathByAddingChild(n);
            collapseAll(tree, path);
        tree.collapsePath(parent);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new HighlightTreeNodeTest().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      private final TreeCellRenderer renderer;
      public String q;
      public MyTreeCellRenderer(TreeCellRenderer renderer) {
        this.renderer = renderer;
      @Override public Component getTreeCellRendererComponent(
          JTree tree, Object value, boolean isSelected, boolean expanded,
          boolean leaf, int row, boolean hasFocus) {
        JComponent c = (JComponent)renderer.getTreeCellRendererComponent(
            tree, value, isSelected, expanded, leaf, row, hasFocus);
        if (isSelected) {
          c.setOpaque(false);
          c.setForeground(getTextSelectionColor());
        } else {
          c.setOpaque(true);
          if (q!=null && !q.isEmpty() && value.toString().startsWith(q)) {
            c.setForeground(getTextNonSelectionColor());
            c.setBackground(Color.YELLOW);
          } else {
            c.setForeground(getTextNonSelectionColor());
            c.setBackground(getBackgroundNonSelectionColor());
        return c;
    }

  • How to add nodes to JTree???

    Hi ,
    i'm developing an application using the NetBeans 6.0. I was trying to add the Nodes on the "JMenuItem" Click event.
    I know how to add the customized code to the JTree, but while adding following code to the JMenuItem's Click, does'nt work
    Code :
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt)
                       DefaultMutableTreeNode dm =new DefaultMutableTreeNode("Root Element");
                       dm.add(new DefaultMutableTreeNode("Child Node"));
                       Treeview=new javax.swing.JTree(dm);
    }        Please help me out where i should write the code so that it will add the nodes to the JTree on JMenuItem's Click.
    Thanks in Advance
    - Hitesh

    Read the tutorial: [Dynamically Changing a Tree|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#dynamic]

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

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

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

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

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

  • 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

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

  • How to rename a column name in a table? Thanks first!

    I tried to drop a column age from table student by writing the
    following in the sql plus environment as :
    SQL> alter table student drop column age ;
    but I found the following error
    ORA-00905: &#32570;&#23569;&#20851;&#38190;&#23383; (Lack of Key word)
    I have oracle enterprise edition 8.0.5 installed at windows 2000
    thank you
    And I want to know how to rename a column name in a table?
    thanks

    In Oracle 8i, your syntax would have worked.  However, if I
    recall correctly, in Oracle 8.0, you can't rename or drop a
    column directly.  One way to get around that problem is to
    create another table based on a select statement from your
    original table, providing the new column name as an alias if you
    want to change the column name, or omitting that column from the
    select statement if you just want to drop it.  Then drop the
    original table.  Then re-create the original table based on a
    select statement from the other table.  Then you can drop the
    other table.  Here is an example:
    CREATE TABLE temporary_table_name
    AS
    SELECT age AS new_column_name,
           other_columns
    FROM   student
    DROP TABLE student
    CREATE TABLE student
    AS
    SELECT *
    FROM   temporary_table_name
    DROP TABLE temporary_table_name
    Something that you need to consider before doing this is
    dependencies.  You need to make a list of all your dependecies
    before you do this, so that you can re-create them afterwards. 
    If there are a lot of them, it might be worthwhile to do
    something else, like creating a view with an alias for the
    column or just providing an alias in a select.  It depends on
    what you need the different column name for.

  • How to Rename a Topic ID in Map File to Avoid Conflict with Another Program?

    Robo 8 HTML:
    Can somebody assist me in understanding how to rename a topic ID in my map.h file?
    An application programmer informs me there are nine topic IDs (shown below) in my project map file which conflict with predefined names of constants/functions from the Visual Studio Libs program and, is requesting I change the names of the topics listed below to resolve topic ID conflict in order to enable F1 call for these topics.
    #define Open    59
    #define Save    60
    #define Print   63
    #define Cut     72
    #define Copy    73
    #define Paste   74
    #define Clear   75
    #define Status  81
    #define Substructure  139
    Can I simply alter the topic names and retain their associated map numbers in <Create/Edit Map ID> dialog to resolve the map file conflict with Visual Studio Libs program functions? Or, is there more work involved in changing a topic name in a map.h file?
    Any assistance with this question is greatly appreciated.
    Thanks,
    robert

    Hi,
    Simply renaming the TopicID's in the .h file won't work. The TopicID is used in the alias file (projectname.ali) to link a map number with a topic. Also, you can use either TopicID's or map numbers to call the help. (Using TopicID's only works for WebHelp afaik.)
    If you use map numbers to call the help, you can rename the TopicID using the mentioned dialog. No problem.
    If you want to change the ID from the files, you have to change both the .h file as the .ali file. No changes to topics needed.

  • How to rename a macbook pro 13 inch 10.7.3 version

    how to rename a macbook pro 13 inch 10.7.3 version?

    As for the Users...
    Go to system preferences - users and groups - click the plus sign - add the name you want.
    Restart your MB - login with your username.
    go back to users and groups - highlight your uncles name - click the minus sign.

Maybe you are looking for

  • Accented characters do not display correctly

    Hello, I created a report in CR with an Oracle8i ODBC connection (version 8.01.74.00). The strange thing is that accented characters are displayed weird in the report although the characters are just fine when I look at them via sqlplus. At first I t

  • Custom KFF on custom form not querying concatenated data

    Hi , A custom form is created ,which has a custom KFF field(which pops up a form with segment field).Both form field and segment1-n fields are based on same table ,the KFF field is inserting data into table,but unable to query concatenaed segment dat

  • Displaying Images In Form Component

    Hi How do I display an employee image in a form Componet, if it is located in file server?? and how do display an employee image in form component if it is saved in the Databse ?? Many Thanks null

  • DW CS3 Index Page animation

    I can only succesfully display an animation on my homepage when I upload the .swf file and companion html file (both published out of Flash 8 Video Encoder), AND the original .fla file (which I used to generate the swf with). Is there a setting I am

  • Authotization Object UIU_COMP

    Hi, does anyone of you have experiences in configuring roles in CRM 2007? It seems that authorization object UIU_COMP is very infuencial to system behaviour. I am looking for a guide or something like this to understand the structure and the possibil