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:
Mým fuckupům
Ubuntu: Login loop
Leaving LinkedIn
LinkedIn: Odcházení
git gui: Add pull and stash commands

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

Last tweets: