Jaroslav Kuboš Jaroslav Kuboš I prefer to discover a causality rather than become a king of Persia. --Democritus

JavaFX: Dynamic context menu on TreeView

01.04.2016

I did not find any simple approach so I had to invent own :-]

package test; 

import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView; 
import javafx.scene.input.MouseButton; 
import javafx.scene.input.MouseEvent; 

//custom implementation of TreeView - but same principle should 
//work on instance of TreeView without inheritance 
public class ObjectsTree extends TreeView<MyNode>{ 
    //custom context menu that can create proper item for selected item 
    //again, custom class is not necessary you can do it on 
    //instance of ContextMenu 
    private DynamicContextMenu menu = new DynamicContextMenu(); 

    public ObjectsTree() { 
        ... 

        addEventHandler(MouseEvent.MOUSE_RELEASED, e->{ 
            if (e.getButton()==MouseButton.SECONDARY) { 
                TreeItem<MyNode> selected = getSelectionModel().getSelectedItem(); 

                //item is selected - this prevents fail when clicking on empty space 
                if (selected!=null) { 
                    //open context menu on current screen position 
                    openContextMenu(selected, e.getScreenX(), e.getScreenY()); 
                } 
            } else { 
                //any other click cause hiding menu 
                menu.hide(); 
            } 
        }); 

        ... 
    } 

    private void openContextMenu(TreeItem<ObjectsTreeNode> item, double x, double y) { 
        //custom method that update menu items 
        menu.setContext(item.getValue()); 

        //show menu 
        menu.show(this, x, y); 
    } 
}

Tagy: Java, JavaFX