JavaFX: Dynamic context menu on TreeView

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); 
    } 
}
Tags:  Java  JavaFX 
Last blog articles:
Why I am not afraid of nowadays technologies
DIY pokus: Destilace z kvasu
Hello Ruby: Dobrodružné programování
Edison EdBlocks: Using remote control
Edison 2.0 received!

Tags:
Java Gradle Ubuntu Software-architecture children React Eclipse DisplayLink DIY AI česky personal Spring JavaScript AspectJ neuron SSH JavaFX Immutables FatJar Edison technologies procrastination pokusy lambda kvas ellipsis destilace chemie alkohol VisualVM Upstart Tomcat Selenium REST PrimeFaces Log4j Jooq Jackson JSF GIT Debug DI CSS

Last tweets: