Context Menu is frequently used with tree if you want to present a very user friendly interface to user like add,delete or enable,disable a tree node. Here i show you how you can add a context menu with add and delete menu items with GXT TreePanel very easily.
Create a new project named GxtContextMenuTree and add GXT library in the project. The tree node objects must possess the functionality of BaseTreeModel of GXT. I have used the same EmployeeTreeNode and Folder class for leaf and parent nodes that i used in my previous blogs related to GXT TreePanel. And in the TestData class i have populated the data to build the tree. You will find the code for these classes here. Create a new package model under the client package and place the EmployeeTreeNode and Folder class there.
final Folder rootNode = TestData.getTreeModel();
final TreeStore<ModelData> store = new TreeStore<ModelData>();
store.add((List) rootNode.getChildren(), true);
final TreePanel<ModelData> tree = new TreePanel<ModelData>(store);
tree.setDisplayProperty("name");
tree.getStyle().setLeafIcon(ICONS.user_add());
tree.setWidth(250);Now create a gxt Menu and add two MenuItem insert and remove with the menu.
Menu contextMenu = new Menu();
contextMenu.setWidth(140);
MenuItem insert = new MenuItem();
insert.setText("Insert Item");
insert.setIcon(ICONS.add());
contextMenu.add(insert);
MenuItem remove = new MenuItem();
remove.setText("Remove Selected");
remove.setIcon(ICONS.delete());
contextMenu.add(remove);What you want to do by clicking on these menu items, just write them in the addSelectionListener method of the MenuItem. Then set the menu to the tree as a context menu by setContextMenu method of the TreePanel.
insert.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
ModelData folder = tree.getSelectionModel().getSelectedItem();
if (folder != null) {
Folder child = new Folder("Add Child " + count++);
store.add(folder, child, false);
tree.setExpanded(folder, true);
}
}
});
remove.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
List<ModelData> selected = tree.getSelectionModel().getSelectedItems();
for (ModelData sel : selected)
{
store.remove(sel);
}
}
});
tree.setContextMenu(contextMenu);
RootPanel.get().add(tree);In the addSelectionListener method of the insert menu item i have written the code for adding a Folder node with the selected node and in the same method of the remove menu item code for removing a list of selected nodes. To view the live demo of this tutorial Click here.
