How to rename the node of a JTree only after clicking pop-up menu item?

99 Views Asked by At

I want to rename the selected node after right-clicking there will be a popup menu containing rename and delete button which will do rename and delete operation after a single click (action listener). And also this popup menu should not be displayed after clicking on any parent node means it must be leaf-node.

here is the Jtree with popup menu with 'rename' item

1

There are 1 best solutions below

2
David Almeida On
node.setUserObject(newName);
panelOfTheTree.repaint();
panelOfTheTree.revalidate();

Regarding the constraint of only being displayed on leaf nodes there are several ways to do this. One way is to implement a MouseListener on the jtree:

tree.addMouseListener(new MouseListener(){
   //...
   @Override
   public void MouseClicked(MouseEvent e){
       if(e.getButton() == MouseEvent.BUTTON3){ //right click
          //get node
          TreePath destinationPath = tree.getClosestPathForLocation(e.getX(), e.getY());
          DefaultMutableTreeNode nodeClicked = (DefaultMutableTreeNode)destinationPath.getLastPathComponent();
          if(nodeClicked .isLeaf()){
               //... build jpopupmenu
          }
               
       }
   }

});