We help IT Professionals succeed at work.

adding popup menu to jtree

umargul
umargul asked
on
I want to add jpopupmenu to the nodes of the jtree. How can i do that?
Comment
Watch Question

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Simply add a mouse listener to your tree and popup you menu when the relevant mouse event is recieved.

Author

Commented:
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

Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
> when the relevant mouse event is recieved.

ie. a right click.

event.getModifiers() & BUTTON3_MASK != 0

or

event.isPopupTrigger()


Mick Barry :)
Brainbench MVP for Java 1
www.brainbench.com

www.objects.com.au


Explore More ContentExplore courses, solutions, and other research materials related to this topic.