Link to home
Start Free TrialLog in
Avatar of umargul
umargul

asked on

adding popup menu to jtree

I want to add jpopupmenu to the nodes of the jtree. How can i do that?
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Simply add a mouse listener to your tree and popup you menu when the relevant mouse event is recieved.
Avatar of umargul
umargul

ASKER

but by simply adding through the mouse listener event the popup menu appears every where in the jtree panel but i want that popup menu should only appear when i right click on any of the node.
Hi,

From the JTree doc:

If you are interested in detecting either double-click events or when a user clicks on a node, regardless of whether or not it was selected, we recommend you do the following:

 final JTree tree = ...;

 MouseListener ml = new MouseAdapter() {
     public void mousePressed(MouseEvent e) {
         int selRow = tree.getRowForLocation(e.getX(), e.getY());
         TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
         if(selRow != -1) {
             if(e.getClickCount() == 1) {
                 mySingleClick(selRow, selPath);
             }
             else if(e.getClickCount() == 2) {
                 myDoubleClick(selRow, selPath);
             }
         }
     }
 };
 tree.addMouseListener(ml);
 
NOTE: This example obtains both the path and row, but you only need to get the one you're interested in.

Put e.isPopupTrigger() instead of e.getClickCount() == 1 and do the same in mousePressed, mouseReleased, mouseClicked--exact event is OS-dependent.

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial