P R
P R

Reputation: 1301

conditional popup menu in jtree

I want a conditional popup menu in jtree based upon which node i right click upon. Is it possible? I implemented it as follows but if I click on node at depth level 1 first it shows correct popup menu but then after if I right click on node at level 2 I still get the same popup menu as for level 1. And similarly vice versa.

DefaultMutableTreeNode node = (DefaultMutableTreeNode) pmTree.getLastSelectedPathComponent();
    popup = new JPopupMenu();
    popup.setInvoker(pmTree);
    PopupHandler handler = new PopupHandler(pmTree, popup);


    if(node.getLevel() == 1)
    {
        popup.add(getMenuItem("Start a VM", handler));
        popup.add(getMenuItem("Monitor all VMs", handler));

    }

    else if(node.getLevel() == 2)
    {
        popup.add(getMenuItem("Change VM configuration", handler));
        popup.add(getMenuItem("Monitor VM", handler));
        popup.add(getMenuItem("Migrate VM", handler));
        popup.add(getMenuItem("Show VM Configuration", handler));
        popup.add(getMenuItem("Stop VM", handler));
    }

Upvotes: 0

Views: 2951

Answers (2)

Eric Rosenberg
Eric Rosenberg

Reputation: 1533

This question appears to be relevant to your situation:

JTree and dropdown options on right clicking nodes

Can you post more of your code?

Its hard to tell without more context but I assume the problem is that the menu is getting built and initialized on the first click but not replaced on the subsequent click.

Upvotes: 2

Tim Wright
Tim Wright

Reputation: 101

This should be possible, try printing out node.getLevel() first to ensure that the level is correct before it enters the conditional code. Since you're creating a new JPopupMenu object each time it doesn't seem that you should need to call removeAll() on popup. Is this code called in a Method each time a node is clicked? Also is it possible that the node at level 1 is shadowing input from the node at level 2?

Upvotes: 1

Related Questions