开发者

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开发者_JS百科 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜