How can I add a right click popup menu to a treeitem in a SWT Tree. Each treeitem should have a right click enabled on it
Adding right click menu to to treeitem in SWT tree
@dic19 I have to use only SWT.Adding a listener to a treeitem with event as SWT.MenuDetect is not working –
Phosphorous
Just use tree.setMenu(Menu)
.
There you go:
public static void main(String[] args)
{
Display display = Display.getDefault();
final Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
final Tree tree = new Tree(shell, SWT.NONE);
for(int i = 0; i < 10; i++)
{
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText("Parent " + i);
for(int j = 0; j < 3; j++)
{
TreeItem child = new TreeItem(item, SWT.NONE);
child.setText("Child " + i + " " + j);
}
}
final Menu menu = new Menu(tree);
tree.setMenu(menu);
menu.addMenuListener(new MenuAdapter()
{
public void menuShown(MenuEvent e)
{
MenuItem[] items = menu.getItems();
for (int i = 0; i < items.length; i++)
{
items[i].dispose();
}
MenuItem newItem = new MenuItem(menu, SWT.NONE);
newItem.setText("Menu for " + tree.getSelection()[0].getText());
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
Is there a way to lock the showing of the menu only for the first level of the tree? For example, to be shown only for the root. –
Pianoforte
@Pianoforte You'd need to add a
MenuDetectListener
to the Tree
and check the level of the item. Then set MenuDetectEvent#doit
to false
if you don't want the menu. Post a new question if you can't get it to work and I'll post a detailed answer. –
Machinist Can you tell me how to get the level of an item of a tree though? –
Pianoforte
@Pianoforte I guess you'll have to call
getParentItem()
on the TreeItem
until it returns null
and count. –
Machinist And where do I have to set the
doit
attribute? Before or after the menu's listener? –
Pianoforte @Pianoforte Inside the
MenuDetectListener
. It's separate from the MenuAdapter
. The MenuDetectListener
will be called first, consequently it can prevent the menu from showing up at all by setting e.doit = false
. –
Machinist I got the concept. Thing is that I've done it like this.
final Menu treeMenu = new Menu(variantTree); variantTree.setMenu(treeMenu); variantTree.addMenuDetectListener(new MenuDetectListener(){ @Override public void menuDetected(MenuDetectEvent event) { // TODO Auto-generated method stub if(variantTree.getParentItem() instanceof TreeItem){ event.doit = false; }else{ event.doit = true; } } });
It doesnt work even though I know the parent is null. Sorry, i was banned to post any questions anymore. –
Pianoforte For the menu to enable, the parent has to be null. –
Pianoforte
© 2022 - 2024 — McMap. All rights reserved.