3
votes

I want to create context menu for treeitems in a treeview. The thing is I want to display different context menu for each treeItem. How to implement this? enter image description here

Foe example I want to create "Add Employee" for Acc Dept and "Add Supporter" for IT support.

Based on name of the treeitem the context menu needs to be displayed.

1
Use a custom Tree Cell and set the context menu on the cell. I have a blog post on doing something similar for a TableView: see if that helps. - James_D
@James_D cool idea, particularly the merging of menuItems :-) Wouldn't have expected that adding a menuItem to several menus would work. Re-parenting seems to happen on showing, not on adding? - kleopatra
MenuItems are not Nodes, so you're not adding the same Node to multiple places in the scene graph. They behave a bit like the items in a ListView or TableView (except there's no menu cell API), you could readily add the same item to multiple ListViews. - James_D
@James_D oops ... assumed (nearly) everything being a Node ... Thanks for the info, made my learn-item of the day :-) - kleopatra
@James_D hmm ... then could we get into trouble with your approach if the graphic property is set on a MenuItem? - kleopatra

1 Answers

2
votes
 public TreeModel() {
        MenuItem addMenuItem = new MenuItem("Create Tab");
        addMenu.getItems().add(addMenuItem);

        addMenuItem.setOnAction(new EventHandler() {
            @Override
            public void handle(Event t) {
                TreeItem newEmployee = 
                    new TreeItem<>("New Tab");
                        getTreeItem().getChildren().add(newEmployee);
            }
        });

        contextMenuProperty().bind(
  Bindings.when(Bindings.equal(itemProperty(),"TABS"))
  .then(addMenu)
  .otherwise((ContextMenu)null));



    }

This works. @James thanks a lot for your excellent article :)