How to use mouse's right click on JTree to pop a menu?

Christopher Brind

Just add a MouseListener to your JTree, then just check if it's the popup trigger.

You'll need to perform the check in both your mousePressed and mouseReleased methods, as the trigger may differ between platforms (some bring up a menu on the press, others on release.

If it is, just call the show method of your popup menu (I assume you have already created this as an instance variable):

public void mousePressed(MouseEvent e) {
    if (e.isPopupTrigger()) {
        popup.show((Component)e.getSource(), e.getX(), e.getY());
    }
}
public void mouseReleased(MouseEvent e) {
    if (e.isPopupTrigger()) {
        popup.show((Component)e.getSource(),e.getX(), e.getY());
    }
}

When a menu item is selected, the popup menu disappears and an ActionEvent is generated for any ActionListeners on that menu item.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact