How do I show different popup menus for different nodes on a JTree?
Created May 4, 2012
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(...); tree.add(menuForNodeType1); JPopupMenu menuForNodeType2 = new JPopupMenu(...); tree.add(menuForNodeType2); JPopupMenu menuForNodeType3 = new JPopupMenu(...); tree.add(menuForNodeType3); 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