Show/Hide JMenuItems in a JPopupMenu based on a JTree's selection

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.


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.

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.


 ? Why this javascript is not working in IE?
 ? Dynamic OLAPCube Flex
 ? What is the problem with linking of Pthreads libraries to .c file in MSVC++6?
 ? C# 4.0 dynamic Office interop performance
 ? PHP(?) or jQuery(?) Best method to change metatags?
 ? Using jQuery to dynamically add form fields (or fieldsets) based on a dropdown box value
 ? C++ - dynamic pointer of array
 ? Delphi: Why can I link this function statically but not dynamically?
 ? Transmit generated XML file without saving to disk
 ? Is there a C# equivalent to Ruby's `respond_to?`?