Selectively editing nodes in a JTree

I need to make certain nodes in a JTree editable, without making every node in the tree editable. How can I accomplish this?

Is there some kind of method in a JTree or a DefaultMutableTreeNode that I can call to select the node's text and be able to change it?Hmm. And you did read the API for JTree looking for such methods before you posted here, didn't you?
So tell us which methods you found to be likely candidates.
db

Similar Messages

  • How to allow multiple selection of nodes in a JTree

    How to allow multiple selection of nodes in a JTree ?
    Thanks
    S.Satish

    By default when you create new instance og JTree the selection model is multiple selection. And if you want to change it you use next:
    tee.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    Hope will help!

  • How to select a node in a JTree by name

    I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help
    Thanks!

    I have a JTree and each node on the JTree has a string name. I also have a JEditorPane that lists all these names at start up. If the user clicks on one of these names, I want to catch the HyperlinkEvent and automatically select that node in the JTree.
    So in short, I have the String name of the node that I want to programatically select.
    Thanks!

  • Select multiple nodes in a JTree a right click

    Hi all,
    I've a JTree and I'd like to allow the user select some nodes (one or more) right click and than show a popupMenu.
    This behavior seems not to be easy, because if I select a single node (right clicking on it) the node does not appear selected ; I need to select it left clicking and than everything works fine.
    I read some posts found in the forum and the solution seems to be :
    - attach a mouseListener to the JTree
    - get the TreePath of the node selected
    - force the selection on the node with setSelectionPath(TreePath)
    This works fine if you need to select only one node, cause if you have to select more, you simply cannot.
    I wonder a so obvious behavior is so hard to achieve.
    I hope somebody out there had made the magic.
    Any help would be appreciated.
    Flavio Palumbo

    Hi Darryl,
    I wrote the test case below.
    Using the methods you suggested it works almost fine.
    The only behavior not desired is when you select a range (shift or control), release the key an than right click ; in this case remains selected the only node you clicked on ; to select the range clicking with the right button, you have to keep pressed the key.
    Any hint would be appreciated.
    Flavio
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    public class TestTree {
        JTree jtr = null;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new TestTree();
        public TestTree() {
            JFrame jf = new JFrame();
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            try {
                javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                javax.swing.SwingUtilities.updateComponentTreeUI(jf);
            } catch (Throwable e) {
            jf.setPreferredSize(new java.awt.Dimension(200, 560));
            javax.swing.JScrollPane js = new javax.swing.JScrollPane();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
            jtr = new JTree(root);
            jtr.addMouseListener(new TestTreeML());
            js.setViewportView(jtr);
            jf.getContentPane().add(js);
            for (int i = 0; i < 20; i++) {
                DefaultMutableTreeNode nodoFiglio = new DefaultMutableTreeNode("nodo" + i);
                ((DefaultTreeModel) jtr.getModel()).insertNodeInto(nodoFiglio, root, root.getChildCount());
            jf.pack();
            jf.setVisible(true);
        public class TestTreeML extends MouseAdapter {
            @Override
            public void mousePressed(MouseEvent e) {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    if (!e.getSource().equals(jtr)) {
                        return;
                    TreePath tpSel = jtr.getPathForLocation(e.getX(), e.getY());
                    if (tpSel == null) {
                        return;
                    int i = 0;
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tpSel.getLastPathComponent();
                    TreePath[] tpExisting = null;
                    if (e.isControlDown() || e.isShiftDown()) {
                        System.out.println("control/shift");
                        TreePath[] tpEx = jtr.getSelectionPaths();
                        tpExisting = java.util.Arrays.copyOfRange(tpEx, 0, tpEx.length + 1);
                        i = tpEx.length;
                    } else {
                        tpExisting = new TreePath[1];
                    tpExisting[i] = tpSel;
                    jtr.setSelectionPaths(tpExisting);
                    if (e.getClickCount() == 2) {
                        System.out.println("double click on " + node.getUserObject());
                    if (javax.swing.SwingUtilities.isRightMouseButton(e)) {
                        if (!e.isControlDown()) {
                            jtr.setSelectionPath(tpSel);
                        JPopupMenu menu = new JPopupMenu();
                        JMenuItem it0 = new JMenuItem("Option1");
                        it0.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                System.out.println("Option1 on " + node.getUserObject());
                        menu.add(it0);
                        JMenuItem it1 = new JMenuItem("Option2");
                        it1.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                System.out.println("Option2 on " + node.getUserObject());
                        menu.add(it1);
                        menu.show(jtr, e.getX(), e.getY());
                } catch (Throwable t) {
    }

  • Selecting a node in a JTree knowing his path

    Hello for all,
    I'm trying to select a specific node in a JTree component by clicking a button.. this is my code :
    private DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("root");
    private DefaultTreeModel treeModel = new DefaultTreeModel(treeNode);
    private JTree tree = new JTree(treeModel);
    private JButton button = new JButton("Select");
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("child1");
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("child2");
    child1.add(new DefaultMutableTreeNode("child11"));
    treeNode.add(child1);
    treeNode.add(child2);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        TreePath path = new TreePath(new Object[]{"root", "child1"});               
        tree.setExpandsSelectedPaths(true);
        tree.scrollPathToVisible(path);
    });as you can see, I want to select the node with the path "root/child1"..
    but I'm getting this exception : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.tree.TreeNode..
    any ideas ?

    You will want to read the second sentence in the TreePath comments section.
    Also, read the second sentence in the TreePath Method Detail section for the
    getLastPathComponent method.
    With these clues &#8212; try getting a TreePath from the tree you are working with.
    For example, you can try something like tree.getPathForRow(row) using the
    visible row index of "child1". Since the TreePath returned comes from the tree
    it will understand what to do with it. You can check the class name of the
    components that are returned in the TreePath to confirm this. And it will
    explain the exception you quoted.

  • JTree and selected tree node

    I am allowing the user to search for a node in a JTree. I can find the node and progamatically expand and select the node. What I would like to do next is find the x,y coordinates of this selected node so I can use Robot to move the mouse to this node. I have hover help which is chock full of information in HTML describing this node, however, the user now is required to move the cursor to this selected node to see the hover help.
    Any help would be appreciated.

    Hi ,
    try this
    jlabel.setIcon( null ) ;

  • How can I edit the selected tree node immediately?

    I have completed a popup menu ,which appeares when I have a mouse rightclicked event
    over the selected tree node.when I selected the popup menu item,i can edit the tree node ,but
    I feel that the tree celleditor appear slowly ,what should i do? the following is my code:
    menuItemRenameNode.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    renameNode_ActionPerformed(ae);
    void renameNode_ActionPerformed(ActionEvent ae){
    setEditable(true);
    this.getCellEditor().addCellEditorListener(new CellEditorListener(){
    public void editingCanceled(ChangeEvent e){
    CellEditor cellEditor =(CellEditor)e.getSource();
    System.out.println("editing canceled:"+cellEditor.getCellEditorValue().toString());
    protected boolean canEditImmediately(EventObject e){
    return true;
    public void editingStopped(ChangeEvent e){
    CellEditor cellEditor =(CellEditor)e.getSource();
    System.out.println("editing stopped:"+cellEditor.getCellEditorValue().toString());

    Please check the suggestions in the thread: https://forums.adobe.com/thread/692020?tstart=0
    Regards,
    | T. Ravi Kumar

  • JTree: editable node

    Hello, I want some help because I have a tree and I want to give the user the possibility to change the selected node value ( to have an editable node with a rightclick).
    I used this methods :
    setEditable (true) and startEditingAtPath()
    But I want to get the new value to change the database and reload the tree. How to do ?
    thanks

    I think I forgot something, Could you say me If I am right ?
    I have a popupmenu "rename" for the tree
    RenameMenuItem.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            Tree.setEditable();
        }); // RenameMenuItem
    [\code]
    and I have the setEditable method :public void setEditable() {
    TreePath treePath = Arborescence.getSelectionPath();
    DefaultTreeModel treeModel = (DefaultTreeModel)myjtree.getModel();
    treeModel.addTreeModelListener(new MyTreeModelListener());
    myjtree.setEditable(true);
    myjtree.startEditingAtPath(treePath);
    }//setEditable
    [\code]
    and mytreemodellistener class
    class MyTreeModelListener implements TreeModelListener {
      public void treeNodesChanged(TreeModelEvent e) {
        DefaultMutableTreeNode node;
        DefaultMutableTreeNode nodee;
        TreePath path = e.getTreePath();
        node = (DefaultMutableTreeNode)(path.getLastPathComponent());
        System.out.println("node 1 ="+node);
        nodee = (DefaultMutableTreeNode
        try {
          int index = e.getChildIndices()[0];
          node = (DefaultMutableTreeNode)(node.getChildAt(index));
          System.out.println("node 2 ="+node);
        catch (NullPointerException exc) {
          System.out.println("TreeModelListener :"+exc.getMessage());
        String newNode =  node.toString();
        System.out.println("New value: " +newNode);
      public void treeNodesInserted(TreeModelEvent e) {
      public void treeNodesRemoved(TreeModelEvent e) {
      public void treeStructureChanged(TreeModelEvent e) {
    }// MyTreeModelListener
    [\code]
    The "node 1" printing in the MyTreeModelListener is the father whereas I change the child and the "node 2" is the child then I don't know how can I retrieve the old name of the child in my database to change its label .
    thanks a lot !                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

  • The selected remote nodes 'node3' are not accessible

    Hello,
    I removed node3 from 2 node RAC Cluster.
    After this I have re-add this node to my RAC. I added without any problem to CRS but I have a problem with script addNode.sh (/u01/app/oracle/product/crs/oui/bin).
    I have to separate homes for ORACLE_HOME and ASM_HOME, so I need to run this script twice for each ORACLE_HOME.
    I run addNode.sh from one of the cluster nodes (node1), if I run:
    export ORACLE_HOME=/u01/app/oracle/product/11.1.0/asm
    cd $ORACLE_HOME/oui/bin
    ./addNode.sh -silent CLUSTER_NEW_NODES={node3} CLUSTER_NEW_PRIVATE_NODE_NAMES={node3-priv} CLUSTER_NEW_VIRTUAL_HOSTNAMES={node3-vip}
    I got the following error:
    Performing tests to see whether nodes node2,node3 are available
    ............................................................SEVERE:The selected remote nodes 'node3' are not accessible.
    ... 100% Done.
    I reviewed logs located in /u01/app/oraInventory/logs I found
    Status of node 'node3':
    null
    The virtual host name 'node3-vip' for node 'node3' is already in use.
    I checked crs_stat from $ORA_CRS_HOME, but all applications (ons, gsd, vip) and targets are ONLINE. I tried to run vipca -nodelist node1,node2,node3 and updated a configuration. I checked /etc/hosts, connection via SSH between all hosts belonging to RAC: node1, node1-vip, node1-priv etc. Everything looks like fine, so I have no idea what caused this problem.
    Software which I used:
    Linux: UNL 5.4 x86_64
    11g Release 11.1.0.7.0 - 64bit, Oracle Clusterware
    Thank you for your answer,
    Best Regards,
    Edited by: user4924714 on 2010-02-15 07:50

    Hi,
    Thanks for your reply.
    I am running addNode.sh from node which already exist in the Rac Cluster. I tried on node1, node2 but the resulat are the same.
    Best regards,

  • Need Help -- How to Change the icon of a selected Tree Node

    Hi java gurus,
    i am working on Jtree application, and i am adding image icons to the Nodes.
    my dought is when i select a node, i want to display that selected node as opened and all other icons should remain closed.
    Example:
    -- root
    |
    ----child
    ----child1
    ----child2
    |
    ----SubChild
    ----SubChild1
    ----subchild2
    Here if i am selecting Child2 means, only the image icon of that child2 should open the nodes and display the icon , all other icons from root to subchild should remain same as closed.
    please some one suggest how i can do it,
    Thanks in advance,
    Cheers,
    Murali

    Stop crossposting!
    http://forum.java.sun.com/thread.jspa?threadID=787916&messageID=4476842#4476842

  • Events of Nodes in a JTree

    Okay, perhaps I am sidetracked today by all the sad craziness occuring in New York and DC, or perhaps I just don't have a grasp on JTrees yet...but...
    I have implemented a TreeCellRender to create panels with buttons and other information to be the nodes of a JTree I created. Everything shows up beautifully, however, I want the buttons on this panel to depress and perfom actions (work like normal) when the user clicks/selects such a button in the tree structure. I can't figure out how to properly set up event handlers to get from the tree to the tree node to the "bean" I'm using as a node. If anyone has any helpful hints, I'd appreciate it!
    Thanks in advance!

    add actionlistener to the JTree, and then get the object by getLastPathComponent, and compare it if its the button and do the action.

  • Hiding / Filtering nodes in a JTree

    I'm not exactly sure how to temporarily hide or filter nodes from a JTree. My scenario is described below.
    I have a radio button group. If the first radio button is selected, all nodes are displayed. If the second button is selected, certain nodes are hidden.
    Here is my attempt to filter nodes. I get the following excpetion when I try to filter nodes:
    java.lang.NullPointerException: Null child not allowed
    I assume this is coming from the getChild() method. I don't know what else to return besides null if I'm trying to filter the node out.
    Can anyone provide some help or insight?
    Thanks
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class MyTreeModel extends DefaultTreeModel
        * Constructor.
        * @param rootNode The root node.
       public MyTreeModel( DefaultMutableTreeNode rootNode )
          super( rootNode );
        * Gets the child node.
        * @param parent The parent node.
        * @param index The index this child node resides in.
        * @return The child node.
       public Object getChild( Object parent, int index )
          Object child = super.getChild( parent, index );
          if ( RadioBtn.hideNodes() )
             DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) child;
             MyNode eNode = ( MyNode ) dmtn.getUserObject();
             if ( !eNode.hasPermission() )
                child = null;    // "hide" the node
          return child;
        * Gets the index of a child.
        * @param parent The parent node.
        * @param child The child node.
        * @return The index of the child node.
        public int getIndexOfChild( Object parent, Object child )
           int index = super.getIndexOfChild( parent, child );
           if ( RadioBtn.hideNodes() )
              DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) parent;
              MyNode eNode = ( MyNode ) dmtn.getUserObject();
              if ( !eNode.hasPermission() )
                 index = -1;
           return index;
        * Returns the number of children attached to the parent node.
        * @param parent The parent node.
        * @return The number of children of the parent node.
       public int getChildCount( Object parent )
          int numChildren = super.getChildCount( parent );
          if ( RadioBtn.hideNodes() )
             int counter = 0;
             DefaultMutableTreeNode dmtn = ( DefaultMutableTreeNode ) parent;
             // Loop through children and keep a count of all children nodes that should stay
             for ( int x = 0; x < numChildren; x++ )
                DefaultMutableTreeNode childDmtn = ( DefaultMutableTreeNode ) dmtn.getChildAt( x );
                MyNode eNode = ( MyNode ) childDmtn.getUserObject();
                if ( eNode.hasPermission() )
                   counter++;
             numChildren = counter;
          System.out.println( "Number of children in " + ( DefaultMutableTreeNode ) parent + ": " + numChildren );
          return numChildren;
        * Used from radio buttons to toggle hidden folders on and off.
       public void triggerMe()
          reload();

    Here it is optimized, for anyone who may need the code down the road.
       public Object getChild( Object parent, int index )
          Object child = super.getChild( parent, index );
          if ( RadioBtn.isHidden() ) // If we should remove the 'special' nodes
             DefaultMutableTreeNode dParent = ( DefaultMutableTreeNode ) parent;
             int count = 0;
             // Loop through children
             for ( int x = 0; x < dParent.getChildCount(); x++ )
                DefaultMutableTreeNode dChild = ( DefaultMutableTreeNode ) dParent.getChildAt( x );
                MyNode eNode = ( MyNode ) dChild.getUserObject();
                if ( eNode.hasPermission() )
                   // If it is the "xth" visible node, break the loop and set this object as the Child node
                   if ( count == index )
                      child = dChild;
                      break;
                   count++;
          return child;
       }

  • Double click a node in a jtree

    hi i have a Jtree with usernames has nodes. how do i generate a code that when a user double clicks a username node, the corresponding code will execute along with what node was clicked on.
    for example, a user clicks on username "jonney" and than a new chat window will appear to establish a chat session with jonney.
    at the moment when a user selects a node, you are able to create a new chat session, but i want to change it so that the user has to double click their username not just selecting it. similar to msn mesenger.
    here is the code i have at the moment.
    public void valueChanged(TreeSelectionEvent event)
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                           userTree.getLastSelectedPathComponent();
              //get username.
              Object nodeInfo = node.getUserObject();
              String info =nodeInfo.toString();
              if(node.isLeaf())
                    ChatDialog_c chatting = new ChatDialog_c(crnt_user, info);
                    Thread t = new Thread(chatting);
                    chatting.setTitle("I-comm");
                    chatting.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    chatting.setSize(430, 200);
                    chatting.getSize();
                    chatting.setLocation(420,200);
                    chatting.setVisible(true);
                    t.start();
          }

    when you call a method you call it on an object.
    e.g.
    Class instance = new Class();
    instance.method();where Class is a hypathetical class name and instance is a hypathetical variable name of type Class.
    new is a keyword for creating an instance of a Class.
    method is the name of a method in Class which is accessable through instance.
    when you do not put an instance in front of a metho call:
    method();it is the same as:
    this.method();this being the keyword to say "us the current object we are in".
    In the API for MouseEvent it says there is a method getClickCount(). looking back at your code we have a refrence to a MouseEvent being passed as a parameter to the method you are in.
    private void userTreeMouseClicked(java.awt.event.MouseEvent evt) {
                                                              ^from this you should be able to see what you are doing wrong, I could have just told you the line to write in much less time but i think you will gain more this way.

  • Highlight the selected Tree Node

    Hello Everyone,
    Can someone plz tell me how to highlight the selected tree node ?
    After selection, user should be able to see which node was last selected.
    Thanks

    Hello,
    for me it is not really clear what you have done. Sorry!
    Because I have problems to paste code, I will describe how you can test that function.
    Take the BSP application HTMLB_SAMPLES and copy it to ZHTMLB_SAMPLES. Take page "treeviewSample.htm" and add the following node behind node22:
    <htmlb:treeNode id   = "node23"
                      text = "Node 2.2, normal text"
                      selection="PRIMARYSELECTION">
    Perhaps this will show you how it works and help you.
    As far as I can see the attribute "selection" can't be set via table.
    Best regads
    Renald
    Edited by: Renald Wittwer on Jan 21, 2010 1:36 PM

  • Selecting multiple nodes of a tree through ctrl+shift

    Can i select multiple nodes of a tree through ctrl+shift.
    How??
    Thanx

    Take a look at JTree#getSelectionModel() and TreeSelectionModel#setSelectionMode(int).
    _myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

Maybe you are looking for

  • Windows 8.1 With Bing or Windows 8.1 Core To Pro Volume License?

    If we buy laptops with Windows 8.1 With Bing or 8.1 Core, what is the path to get Windows 8.1 Pro volume licensing so we can join them to domains and create a common MDT deployment image? Do we buy a Pro Pack license for each system and then use the

  • Why is my iSight camera is not working with the new Mac Pro?

    I connected the iSight camera which is a FireWire 400 into a Sonnet FireWire 800 adapter, and connected that into a FireWire to ThunderBolt adapter and plugged directly into the Mac Pro running Mave. I receive power, noted by the green light coming o

  • Why won't my imac dvd drive accept disk?

    My 21 inch iMac won't accept a dvd or cd. Is this a hardware or software issue, and what do I do?

  • Finder disappears.... ???

    There's a glitch in my Finder??? I was watching a DVD, using DVD Player - I got bored, so I stopped the DVD, quit the Application, ejected the disc by dragging the icon to the eject thing in the Dock - then I had the Finder window open with the appli

  • Processkey on 2LIS_02_ITM

    Hi SDN, We have a few PO for which in BI there are records with processkey 002 and 003 but none with processkey 001. Is it possible? If so, in what circumstances 2LIS_02_ITM may not bring records for processkey 001? Thanks for the help. SM