views:

294

answers:

2

I have a JTree which displays a JPopupMenu when I right click nodes in the JTree. What is the best way to hide/show or enable/disable certain JMenuItems in my JPopupMenu based on the node selected in the JTree?

The first solution that came to mind was to add a TreeSelectionListener to the JTree for the 'value changed' event. In the event handling code I would use the TreeSelectionEvent's getNewLeadSelectionPath() method to get the path of the most recent selection, and use the resulting TreePath object's getLastPathComponent() to get the selected node. From here I would have a series of IF statements that access my JPopupMenu object and perform the modifications necessary to hide/show specific JMenuItems.

However, something feels off about this, and so I decided I would ask SO if there was a better approach.

+1  A: 

Getting the selected tree node is straight forward and should work as you described it. To modify the popup menu I would recommend using Actions. This way you wouldn’t have to modify your live menu and could also add e.g. a JToolBar that contains the same actions that react the same way the items in your menu do.

Bombe
+1  A: 

The way that I chose to tackle this within my own app was to use the "userObject" property of the DefaultMutableTreeNode class which allows you to just store any data you want along with your node. I have a variety of types of things that extend from an abstract base class which defines a "createPopupMenu()" method. Then, in the selection listener (just as you described in your question) I get the user object and ask it to create a popup menu appropriate for the selected object and display that.

BryanD