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);
  } 
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s