How do I show different popup menus for different nodes on a JTree?

Sandip Chitale

The problem boils down to finding out the tree node at the point of popupTrigger event (could be right-mouse-button down or other combinations depending on the platform - therefore you must always use mouseEvent.isPopupTrigger() API to find that out). Now to find the tree node at the point use the following API -

// Create different for each type of node node
// for which to a distinct popup and add to the tree

JPopupMenu menuForNodeType1 = new JPopupMenu(...);
JPopupMenu menuForNodeType2 = new JPopupMenu(...);
JPopupMenu menuForNodeType3 = new JPopupMenu(...);

int row = tree.getRowAtLocation(mouseX, mouseY);
TreePath tp = tree.getPathForRow(row);
Object node = tp.getLastPathComponent();

// now locate the right popup menu
// and show it ay mouseX, mouseY
0 Comments  (click to add your comment)
Comment and Contribute






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



About | Sitemap | Contact